gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:54:17 24 4
gpt4 key购买 nike

当我在 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

如果您能帮助我尝试调试此问题并了解我哪里出错了,我将不胜感激。

最佳答案

问题是数据被压缩了。

要修复它,而不必自己解压缩数据,请指示 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 :

Additionally, all API responses are compressed.

关于c# - C# 中的 HTTP 调用在响应中返回垃圾数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45831967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com