ReadAsByteArrayAsync返回不可读

时间:2019-07-23 11:09:16

标签: c# .net get

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

我尝试使用不同的阅读方法,例如ReadAsStringAsync(),我尝试将其转换为UTF-8,我设置了mediaType文本/纯文本,我试图转换为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 个答案:

答案 0 :(得分:1)

我看到缺少请求接受标头的问题!将accept标头设置为收到的响应将不起作用。请尝试以下代码。

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

答案 1 :(得分:0)

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

,它可以正常工作。