用户登录
用户注册

分享至

HttpClient GetStreamAsync 和 HTTP 状态代码?

  • 作者: 小猪666
  • 来源: 51数据库
  • 2023-02-13

问题描述

我希望按照 json.net 性能提示文档的推荐使用流,但是我无法找到如何在没有 典型的等待 HttpResponse.

I wish to use streams as recommended by the json.net performance tips documentation, however I'm unable to find how to get a hold of the http status codes without the typical awaiting the HttpResponse.

有没有办法先获取状态码而不读取数据?所以还在利用流?

Is there perhaps a way of getting the status code first without reading the data? So still taking advantage of streams?

推荐答案

我还没有测试以确保它的性能,但是这看起来很有希望:

I haven't tested to ensure it's performance, however this seems promising:

using(HttpClient client = new HttpClient())
{
    var response = await client.GetAsync("http://www.51sjk.com/Upload/Articles/1/0/343/343141_20230213091623386.jpg", HttpCompletionOption.ResponseHeadersRead);

    response.EnsureSuccessStatusCode();

    using (var stream = await response.Content.ReadAsStreamAsync())
    using (var streamReader = new StreamReader(stream))
    using (var jsonReader = new JsonTextReader(streamReader))
    {
      var serializer = new JsonSerializer();

       //do some deserializing http://www.51sjk.com/Upload/Articles/1/0/343/343141_20230213091623823.htm
    }
}
软件
前端设计
程序设计
Java相关