亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 260 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號