c# - Windows Phone 7 上的 HttpWebRequest

标签 c# .net windows-phone-7 httpwebrequest

我有这个代码:

        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 error

可能是什么问题?

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

谢谢, 帕维尔.

最佳答案

您的代码中有两个问题。

  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;
        ...
    }
    

关于c# - Windows Phone 7 上的 HttpWebRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10666542/

相关文章:

c# - ViewModel 返回默认值 0

c# - 显示 WinForms 对话框后,System.Progress 未在主线程上触发事件

.net - 新应用程序的数据层 : MyGeneration and/or Entity-Framework

windows-phone-7 - WP7 - 根据设置动态更改启动页面

c# - 继承自 IEnumerable

c# - 防止在 Entity Framework 中的相关表实体上添加新记录

c# - 在 ASP.NET 条形图中显示持续时间

C#:Math Round() 对于不同的小数会产生不同的值

windows-phone-7 - 参数不正确。在 MS.Internal.XcpImports.MethodEx(IntPtr ptr,字符串名称,CValue[] cvData)

c# - 为什么只有整数枚举?