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: ������
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With