为了账号安全,请及时绑定邮箱和手机立即绑定

ReadAsByteArrayAsync 返回不可读

ReadAsByteArrayAsync 返回不可读

C#
繁星淼淼 2023-07-09 17:56:33
我正在编写应用程序.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}
查看完整描述

2 回答

?
哆啦的时光机

TA贡献1779条经验 获得超6个赞

我没有意识到,该响应是 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();

}

并且它工作正常。


查看完整回答
反对 回复 2023-07-09
?
狐的传说

TA贡献1804条经验 获得超3个赞

我发现缺少请求接受标头的问题!将接受标头设置为收到的响应是行不通的。尝试下面的代码。


  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);

  }


查看完整回答
反对 回复 2023-07-09
  • 2 回答
  • 0 关注
  • 207 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信