8

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

svick
  • 236,525
  • 50
  • 385
  • 514
Adrian
  • 19,440
  • 34
  • 112
  • 219
  • Why does that "force" you to use HttpClient? – Matti Virkkunen Feb 11 '12 at 17:51
  • There is no such thing as Visual Studio 2011. Do you mean Visual Studio 11 Developer Preview? And no version of Visual Studio forces you to use `HttpClient`. What exactly do you mean by that? Are you developing a Metro-style app? – svick Feb 11 '12 at 17:52
  • I guess he is working on a Metro style application and there's no longer a `WebClient` class in `WinRT`. – Darin Dimitrov Feb 11 '12 at 17:53
  • I think you can still use `WebRequest`. Also, I think the problem is that `HttpClient` doesn't automatically decompress gzipped data. – svick Feb 11 '12 at 18:00
  • I can use WebRequest too, but I find it much complicated (I have to use BeginGetResponse() witch is asynchronous). – Adrian Feb 11 '12 at 18:03

1 Answers1

32

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
        });
Community
  • 1
  • 1
svick
  • 236,525
  • 50
  • 385
  • 514
  • very helpful after hours of searching about wrong characters in response. I first thought that it is due to encoding! but it was gzip! – S.Serpooshan Jun 02 '23 at 19:29