简体   繁体   English

HttpClient和Windows Phone 8便携式

[英]HttpClient and windows phone 8 portable

I'm having a very strange problem. 我有一个非常奇怪的问题。 I trying to do a WP8.0 application that uses a portable library. 我试图做一个使用可移植库的WP8.0应用程序。 In this portable library, I'm using restsharp portable and everything was fine until instead of POSTs I started to do GETs. 在这个可移植的库中,我正在使用restsharp Portable,一切都很好,直到我开始执行GET而不是POST为止。 Going deeper, I found that the problem is in HttpClient, so I did a simple code just with HttpClient and found that using the same code in the following scenarios the results vary: * in WP8+portable GET doesn't work, the call doesn't return but POST works fine * in WP81 OK 更深入地讲,我发现问题出在HttpClient中,所以我只用HttpClient做了一个简单的代码,发现在以下情况下使用相同的代码,结果会有所不同:*在WP8 +便携式GET中不起作用,调用不起作用不返回但POST可以正常工作*在WP81中可以

I'm doing GET's to www.google.com and the POSTs to my own server. 我正在对www.google.com进行GET,对我自己的服务器进行POST。 I am using the WP8.1 emulator for the tests. 我正在使用WP8.1仿真器进行测试。

Any idea? 任何想法?

Found the problem! 发现了问题!

The code I was using to test was this: 我用来测试的代码是这样的:

  using (var client = new HttpClient())
  {
       client.BaseAddress = new Uri("http://www.google.es/");
       client.DefaultRequestHeaders.Clear();
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
       HttpResponseMessage response = client.GetAsync("").Result;
       if (response.IsSuccessStatusCode)
       {
         text = response.Content.ReadAsStringAsync().Result;
       }
  }

The problem is using Result in GetAsync. 问题是在GetAsync中使用Result。 I don't know why but it worked fine if I changed to await client.GetAsync(""); 我不知道为什么,但是如果我更改为等待client.GetAsync(“”);,它会很好地工作。

In my app, I have the code with await BUT the top level method wasn't async and I use .Result. 在我的应用程序中,我有等待代码,但顶级方法不是异步的,我使用.Result。 The solution is not to use .Result when calling an async method (I don't know if it applies to every method or just HttpClient methods). 解决方案是在调用异步方法时不使用.Result(我不知道它是否适用于每个方法或仅适用于HttpClient方法)。 The POST worked fine because they are in async methods. POST运作良好,因为它们处于异步方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM