问题
I am programming for Visual Studio 2011 so I am forced to use HttpClient
. I need to retrieve some JSON data from the web, but I guess I need to set the content to "json data" or something because I always get strange characters when using only this code:
HttpClient client = new HttpClient();
var response = client.Get("http://api.stackoverflow.com/1.1/users");
var content = response.Content.ReadAsString();
So how can I set the content or what should I do to get the correct data ?
edit:
Output: something like this: ������
回答1:
The problem is that the response is compressed and HttpClient
does not automatically decompress it by default.
With WebClient
, you can create a derived class and set the AutomaticDecompression of the underlying HttpWebRequest.
You can't do that with HttpClient
, because it doesn't have any suitable virtual
methods. But you can do it by passing HttpClientHandler to its constructor:
var client =
new HttpClient(
new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip
| DecompressionMethods.Deflate
});
来源:https://stackoverflow.com/questions/9242472/retrieve-json-data-with-httpclient