我在WP7应用程序中遇到基本的HttpWebRequest问题。一旦我调用BeginGetRequestStream,它就会出错。然后,回调方法会收到IAsyncResult
,但没有AsyncWaitHandle
。
AsyncWaitHandle ='ar.AsyncWaitHandle'抛出了'System.NotSupportedException'类型的异常
我在下面创建了一个产生错误的示例。为了创建这个,我刚刚采用了示例数据透视应用程序,并试图将一些数据发布到MainViewModel的构造函数中的服务器上。
public MainViewModel()
{
this.Items = new ObservableCollection<ItemViewModel>();
HttpWebRequest webRequest = WebRequest.CreateHttp("http://www.google.co.uk");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.BeginGetRequestStream(BeginGetRequestStreamCallBack, webRequest);
}
private void BeginGetRequestStreamCallBack(IAsyncResult ar)
{
HttpWebRequest webRequest = (HttpWebRequest) ar.AsyncState;
Stream requestStream = webRequest.EndGetRequestStream(ar);
using(StreamWriter sw = new StreamWriter(requestStream))
{
sw.Write("{ test: \"test\" }");
}
webRequest.BeginGetResponse(BeginGetResponseCallback, webRequest);
}
private void BeginGetResponseCallback(IAsyncResult ar)
{
HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;
WebResponse webResponse = webRequest.EndGetResponse(ar);
Stream responseStream = webResponse.GetResponseStream();
string whatCameBack = new StreamReader(responseStream).ReadToEnd();
}
任何帮助都将一如既往,非常感谢。
我已经深入研究了这一点,我似乎无法使用BeginGetRequestStream
发布数据。
public MainViewModel()
{
this.Items = new ObservableCollection<ItemViewModel>();
HttpWebRequest webRequest = WebRequest.CreateHttp("http://www.google.co.uk");
//webRequest.Method = "POST";
//webRequest.ContentType = "application/x-www-form-urlencoded";
//webRequest.BeginGetRequestStream(BeginGetRequestStreamCallBack, webRequest);
webRequest.BeginGetResponse(BeginGetResponseCallback, webRequest);
}
private void BeginGetRequestStreamCallBack(IAsyncResult ar)
{
HttpWebRequest webRequest = (HttpWebRequest) ar.AsyncState;
Stream requestStream = webRequest.EndGetRequestStream(ar);
using(StreamWriter sw = new StreamWriter(requestStream))
{
sw.Write("{ test: \"test\" }");
}
webRequest.BeginGetResponse(BeginGetResponseCallback, webRequest);
}
private void BeginGetResponseCallback(IAsyncResult ar)
{
HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;
WebResponse webResponse = webRequest.EndGetResponse(ar);
Stream responseStream = webResponse.GetResponseStream();
string whatCameBack = new StreamReader(responseStream).ReadToEnd();
}
这没关系,但这不是我想要的。
有什么想法吗?
答案 0 :(得分:0)
我是一个顽皮的男孩,而不是正确关闭流。
using(Stream requestStream = webRequest.EndGetRequestStream(ar))
{}
一切都很好。