C#中的HTTP调用返回响应中的垃圾数据

时间:2017-08-23 06:16:46

标签: c# rest http

当我在C#中发出HTTP请求并读取响应时,我在响应中获取了垃圾数据。我无法弄清楚这个问题。请考虑以下示例代码段,其中我调用了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");
}

下面的屏幕截图说明了我收到的垃圾输出:

garbage output from HTTP request

我非常感谢您尝试调试此问题并了解我出错的地方。

1 个答案:

答案 0 :(得分:3)

问题是数据被压缩了。

要修复它,无需自行解压缩数据,请指示HttpClient为您执行此操作:

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

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

然后您的代码会提供此输出(缩写):

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

这也是documented

  

此外,所有API响应都已压缩。