5

When I am making HTTP requests in C# and reading the response, I am getting garbage data in the response. I am unable to figure out the problem. Consider the following example snippet where I make a call to the Stack Exchange API.

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://api.stackexchange.com/info");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = client.GetAsync("?site=stackoverflow").Result;

if (response.IsSuccessStatusCode)
{
    Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
else
{
    Console.WriteLine("Sorry");
}

The screenshot below illustrates the garbage output I am receiving:

garbage output from HTTP request

I'd appreciate any help in trying to debug this issue and knowing where I went wrong.

pratnala
  • 3,723
  • 7
  • 35
  • 58

1 Answers1

13

The problem is that the data is compressed.

To fix it, without having to decompress the data yourself, instruct HttpClient to do it for you:

HttpClientHandler handler = new HttpClientHandler()
{
    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};

HttpClient client = new HttpClient(handler);
// ... rest of your code here

Your code then gives this output (abbreviated):

{"items":[{"new_active_users":13,"total_users":7599686,"badges_per_minute":5.04,"total_badges":24036822,...

This is also documented:

Additionally, all API responses are compressed.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825