gpt4 book ai didi

c# - HttpClient 响应返回乱码数据

转载 作者:行者123 更新时间:2023-12-02 19:19:46 24 4
gpt4 key购买 nike

我正在尝试使用 HttpClient 从此 URL 获取正确的 JSON 响应。当我在 Chrome 中查看 URL 时,数据是正确格式的 JSON。当我使用 HttpClient 时,我收到一堆看起来像字节或类似内容的垃圾数据。我不知道如何将其解码为字符串。请指教。

string url = "https://api.nasdaq.com/api/calendar/earnings?date=2010-07-30";

string calendar = await DownloadFile(new string[] { url });

private static readonly HttpClient httpClient = new HttpClient();

public static async Task<string> DownloadFile(string[] args)
{
string url = args[0];

httpClient.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, br");
httpClient.DefaultRequestHeaders.Connection.ParseAdd("keep-alive");

string text = await httpClient.GetStringAsync(url);

return text;

}

最佳答案

返回的数据是使用 gzip 压缩的。通过在实例化 HttpClient 时启用此属性,您可以让 HttpClient 自动解压缩此数据:

    private static readonly HttpClient httpClient = new HttpClient(new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
});

关于c# - HttpClient 响应返回乱码数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63224153/

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