Retrieve Json data with HttpClient

◇◆丶佛笑我妖孽 提交于 2020-01-01 05:21:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!