我有这个code:
private HttpWebRequest request;
private HttpWebResponse wResponse;
private CookieContainer cookieContainer = new CookieContainer();
#region PRIVATE METHODS
private void RunRequest(string url)
{
request = HttpWebRequest.Create(new Uri(url)) as HttpWebRequest;
request.UserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.205 Safari/534.16";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookieContainer;
request.Method = "GET";
StartWebRequest(request);
//Do smthng
while (wResponse == null) { }
}
private void StartWebRequest(HttpWebRequest request)
{
request.BeginGetResponse(FinishWebRequest, request);
}
private void FinishWebRequest(IAsyncResult result)
{
wResponse = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
}
#endregion
和wRequest变量不填充任何回应。在AsyncState我有这样的:
And wRequest variable is not filled with any response. In AsyncState I have this:
这可能是什么问题?
P.S。同样的code工作好上了桌面应用程序。
p.s. The same code works good on the desktop-app.
谢谢, 帕维尔。
有在code两个问题。
There are two problems in your code.
您没有正确使用异步回调方法:
You are not properly using asynchronous callback method:
替换
request.BeginGetResponse(FinishWebRequest,请求);
与
request.BeginGetResponse(新的AsyncCallback(FinishWebRequest),请求);
指定的Content-Type GET请求是无效的,这是至关重要的
对于POST请求。修改 RunRequest()
方法:
Specifying Content-Type for GET request is invalid, it is essential
for POST request. Modify RunRequest()
method:
private void RunRequest(string url, string method)
{
request = HttpWebRequest.Create(new Uri(url)) as HttpWebRequest;
request.UserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.205 Safari/534.16";
request.Method = method; // method can be GET, POST etc.
if (method == "POST")
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookieContainer;
...
}