我正在尝试使用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
});
我认为您必须从请求头中删除Brotli压缩。Brotli(br(未被.Net.开箱即用解码
也就是说,改变:
httpClient.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, br");
至
httpClient.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate");