我正在从我的原始帖子(Windows Phone 8 的 Http Post)中重新发布第二个问题,因为我的主要问题已经得到回答。
这是我在@Hunter McMillen 的帮助下更新的代码。我现在正试图从服务器获取 responseCallback。问题是GetResponseCallback => (HttpWebResponse)httpWebRequest.EndGetResponse(GetResponseCallback)
第二个 using 语句中的行,它正在显示
An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll but was not handled in user code
If there is a handler for this exception, the program may be safely continued.
这个错误发生在我使用第一个示例之前。有谁知道如何解决这个问题?
private static async void HttpPostData(){
string url = "http://www.mytunnel.com/api/purchases";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/plain";
//httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.AllowWriteStreamBuffering = true;
httpWebRequest.Method = "POST";
//httpWebRequest.ContentLength = jsonAsBytes.Length;
try{
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream, httpWebRequest.EndGetRequestStream, null))
{
byte[] jsonAsBytes = Encoding.UTF8.GetBytes("{ \"data\" : \"json\" }");
await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}
}
catch (Exception e) { Debug.WriteLine(e.Message); }
httpWebRequest.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), httpWebRequest);
}
private static void ReadWebRequestCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = callbackResult.AsyncState as HttpWebRequest;
try
{
HttpWebResponse response = myRequest.EndGetResponse(callbackResult) as HttpWebResponse;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
String s = sr.ReadToEnd();
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show(s); });
}
}
catch (WebException webExcp)
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show(webExcp.ToString()); });
}
}