Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve Json data with HttpClient

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: ������

like image 980
Adrian Avatar asked Feb 11 '12 17:02

Adrian


1 Answers

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
        });
like image 179
svick Avatar answered Sep 17 '22 17:09

svick