热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

HttpClientGetStreamAsync和HTTP状态代码?-HttpClientGetStreamAsyncandHTTPstatuscodes?

Iwishtousestreamsasrecommendedbythejson.netperformancetipsdocumentation,howeverImuna

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.

我希望按照json.net性能提示文档的建议使用流,但是我无法找到如何获取http状态代码而没有典型的等待HttpResponse。

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

是否有一种方法可以在不读取数据的情况下首先获取状态代码?所以仍然利用流?

2 个解决方案

#1


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

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

using(HttpClient client = new HttpClient())
{
    var respOnse= await client.GetAsync("http://httpbin.org/get", 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.newtonsoft.com/json/help/html/Performance.htm
    }
}

#2


I prefer to dispose of the HttpResponseMessage via using as it is disposable. I also prefer to not rely on exception handling to deal with failed requests. Instead I prefer to check against the IsSuccessStatusCode boolean value and proceed accordingly. For example:

我喜欢通过使用HttpResponseMessage来处理它,因为它是一次性的。我也更喜欢不依赖异常处理来处理失败的请求。相反,我更喜欢检查IsSuccessStatusCode布尔值并相应地继续。例如:

using(HttpClient client = new HttpClient())
{
    using(var respOnse= await client.GetAsync("http://httpbin.org/get", HttpCompletionOption.ResponseHeadersRead))
    {
        if(response.IsSuccessStatusCode)
        {
            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.newtonsoft.com/json/help/html/Performance.htm
            }
        }
        else {
            //do your error logging and/or retry logic
        }
    }       
}

EDIT: If you're doing work with a rate limited api sending the HEAD request just isn't sometimes feasible. As such, here's a code sample using the good ol' fashion HttpWebRequest (note that there isn't a better way to deal with http errors than WebException in this case):

编辑:如果您正在使用速率有限的api进行工作,发送HEAD请求有时是不可行的。因此,这里是使用好的'时尚HttpWebRequest的代码示例(请注意,在这种情况下,没有比WebException更好的方法来处理http错误):

var req = WebRequest.CreateHttp("http://httpbin.org/get");

/*
 * execute
 */
try
{
    using (var resp = await req.GetResponseAsync())
    {
        using (var s = resp.GetResponseStream())
        using (var sr = new StreamReader(s))
        using (var j = new JsonTextReader(sr))
        {
            var serializer = new JsonSerializer();
            //do some deserializing http://www.newtonsoft.com/json/help/html/Performance.htm
        }
    }
}
catch (WebException ex)
{
    using (HttpWebResponse respOnse= (HttpWebResponse)ex.Response)
    {
        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
        {
            string respStr = sr.ReadToEnd();
            int statusCode = (int)response.StatusCode;

            //do your status code logic here
        }
    }
}

推荐阅读
author-avatar
小杰01234
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有