ReadAsByteArrayAsync 返回不可读

我正在编写应用程序.NET,我需要从一些 api 获取数据。


我尝试使用不同的阅读方法,例如ReadAsStringAsync(),我尝试将它们转换为UTF-8,我设置 mediaType text/plain ,我尝试转换为JSON,但在解析过程中引发了错误。


HttpClient client = new HttpClient();

client.DefaultRequestHeaders.Accept.Clear();

byte[] responded;

HttpResponseMessage response = await client.GetAsync(path);

response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

if (response.IsSuccessStatusCode)

{

    response.Content.ReadAsByteArrayAsync().Wait();

    responded =  response.Content.ReadAsByteArrayAsync().Result;

    var responseString = Encoding.UTF8.GetString(responded, 0, responded.Length);

    Console.WriteLine("\n " +responseString);

}

我得到回应:


?0E?%?}S??WDJpq?%)X??}???s????A???BK?X?}?k

但这不是我所期望的:


{"items:[{"has_synonyms":true,"is_moderator_only":false,"is_required":false,"count":9452,"name":"tags"}],"has_more":false,"quota_max":300,"quota_remaining":296}


繁星淼淼
浏览 208回答 2
2回答

哆啦的时光机

我没有意识到,该响应是 gzip 格式。我做了更改:Stream responded;HttpResponseMessage response = await client.GetAsync(new Uri(path));if (response.IsSuccessStatusCode){        response.Content.ReadAsStringAsync().Wait();        responded = response.Content.ReadAsStreamAsync().Result;        Stream decompressed = new GZipStream(responded, CompressionMode.Decompress);        StreamReader objReader = new StreamReader(decompressed, Encoding.UTF8);        string sLine;        sLine = objReader.ReadToEnd();}并且它工作正常。

狐的传说

我发现缺少请求接受标头的问题!将接受标头设置为收到的响应是行不通的。尝试下面的代码。  HttpClient client = new HttpClient();  client.DefaultRequestHeaders.Accept.Clear();  client.DefaultRequestHeaders.Accept.Add(new MediaTypeHeaderValue("application/json"));  byte[] responded;  HttpResponseMessage response = await client.GetAsync(path);  if (response.IsSuccessStatusCode)  {        response.Content.ReadAsByteArrayAsync().Wait();        responded =  response.Content.ReadAsByteArrayAsync().Result;        var responseString = Encoding.UTF8.GetString(responded, 0, responded.Length);        Console.WriteLine("\n " +responseString);  }
打开App,查看更多内容
随时随地看视频慕课网APP