Windows手机httpclient无法正常工作

时间:2014-02-26 17:11:21

标签: windows-phone-8

我有以下代码。异步调用永远不会返回任何内容。即使是google.com。

try
            {
                using (
                    var client = new HttpClient()) { 
                var response = client.GetAsync("http://www.google.com");
                Debug.WriteLine("Coming here1"+response.Result.IsSuccessStatusCode);
                if (response.Result.IsSuccessStatusCode)
                {
                    // by calling .Result you are performing a synchronous call
                    Debug.WriteLine("Coming here1");
                    var responseContent = response.Result.Content;

                    // by calling .Result you are synchronously reading the result
                    string responseString = responseContent.ReadAsStringAsync().Result;

                    //Console.WriteLine(responseString);
                }
                else { Debug.WriteLine("else"); }
            }
            }
            catch(Exception e)
            {
               Debug.WriteLine(e.ToString());
            }
        }

2 个答案:

答案 0 :(得分:0)

试试这个

try{
     WebClient wc = new WebClient();
     wc.DownloadStringCompleted+= (sender,args) => {
        Debug.WriteLine(args.results);
     };
     wc.DownloadStringAsync(new Uri(@"http://www.Google.com",UriKind.RelativeOrAbsolute));

}
catch(Exception e){ Debug.WriteLine(e.Message); }

答案 1 :(得分:0)

您似乎没有等待异步通话。

尝试将var response = client.GetAsync("http://www.google.com");更改为var response = await client.GetAsync("http://www.google.com");

请务必将您的方法标记为async

您还在阻止异步通话ReadAsStringAsync().Result。与client.GetAsync一样,请确保等待调用而不是使用Result进行阻止。这个blog post就这个话题说了一点。

在async / await上读一点。一旦掌握了它,你就会爱上它。