【问题标题】:Windows phone httpclient not workingWindows 手机 httpclient 不工作
【发布时间】:2014-02-26 17:11:20
【问题描述】:

我有以下代码。异步调用从不返回任何内容。即使是 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());
            }
        }

【问题讨论】:

标签: windows-phone-8


【解决方案1】:

试试这个

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

【讨论】:

  • 当然。如果您遇到任何如何在手机上使用 Httpclient 的教程,请告诉我
  • 但我想到了 HttpClient 选项..这是工作代码codeString strResult = await signUpReq.GetStringAsync(finalUri);code
【解决方案2】:

您似乎没有在等待您的异步调用。

尝试将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 的内容。一旦你掌握了它,你就会爱上它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多