2

我有这个代码:

        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 我有这个: HttpWebRequest 错误

可能是什么问题呢?

ps 相同的代码在桌面应用程序上运行良好。

谢谢,帕维尔。

4

2 回答 2

2

您的代码中有两个问题。

  1. 您没有正确使用异步回调方法:

    代替

    request.BeginGetResponse(FinishWebRequest, request);

    request.BeginGetResponse(new AsyncCallback(FinishWebRequest), request);

  2. 为 GET 请求指定 Content-Type 是无效的,这对于 POST 请求是必不可少的。修改RunRequest()方法:

    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;
        ...
    }
    
于 2012-05-19T17:09:18.830 回答
1

使用 GET 操作时没有理由指定 ContentType;删除它应该可以解决问题!

于 2012-05-19T15:49:41.353 回答