热门标签 | 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
        }
    }
}

推荐阅读
  • 使用 Azure Service Principal 和 Microsoft Graph API 获取 AAD 用户列表
    本文介绍了一段通用代码示例,该代码不仅能够操作 Azure Active Directory (AAD),还可以通过 Azure Service Principal 的授权访问和管理 Azure 订阅资源。Azure 的架构可以分为两个层级:AAD 和 Subscription。 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • dotnet 通过 Elmish.WPF 使用 F# 编写 WPF 应用
    本文来安利大家一个有趣而且强大的库,通过F#和C#混合编程编写WPF应用,可以在WPF中使用到F#强大的数据处理能力在GitHub上完全开源Elmis ... [详细]
  • 深入理解Shell脚本编程
    本文详细介绍了Shell脚本编程的基础概念、语法结构及其在操作系统中的应用。通过具体的示例代码,帮助读者掌握如何编写和执行Shell脚本。 ... [详细]
  • 本文详细介绍了网络存储技术的基本概念、分类及应用场景。通过分析直连式存储(DAS)、网络附加存储(NAS)和存储区域网络(SAN)的特点,帮助读者理解不同存储方式的优势与局限性。 ... [详细]
  • Python处理Word文档的高效技巧
    本文详细介绍了如何使用Python处理Word文档,涵盖从基础操作到高级功能的各种技巧。我们将探讨如何生成文档、定义样式、提取表格数据以及处理超链接和图片等内容。 ... [详细]
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • 本文介绍了如何利用JavaScript或jQuery来判断网页中的文本框是否处于焦点状态,以及如何检测鼠标是否悬停在指定的HTML元素上。 ... [详细]
  • 导航栏样式练习:项目实例解析
    本文详细介绍了如何创建一个具有动态效果的导航栏,包括HTML、CSS和JavaScript代码的实现,并附有详细的说明和效果图。 ... [详细]
  • 深入理解Cookie与Session会话管理
    本文详细介绍了如何通过HTTP响应和请求处理浏览器的Cookie信息,以及如何创建、设置和管理Cookie。同时探讨了会话跟踪技术中的Session机制,解释其原理及应用场景。 ... [详细]
  • 本文介绍了如何使用JQuery实现省市二级联动和表单验证。首先,通过change事件监听用户选择的省份,并动态加载对应的城市列表。其次,详细讲解了使用Validation插件进行表单验证的方法,包括内置规则、自定义规则及实时验证功能。 ... [详细]
  • 本文详细介绍了Java中org.eclipse.ui.forms.widgets.ExpandableComposite类的addExpansionListener()方法,并提供了多个实际代码示例,帮助开发者更好地理解和使用该方法。这些示例来源于多个知名开源项目,具有很高的参考价值。 ... [详细]
  • 在前两篇文章中,我们探讨了 ControllerDescriptor 和 ActionDescriptor 这两个描述对象,分别对应控制器和操作方法。本文将基于 MVC3 源码进一步分析 ParameterDescriptor,即用于描述 Action 方法参数的对象,并详细介绍其工作原理。 ... [详细]
  • DNN Community 和 Professional 版本的主要差异
    本文详细解析了 DotNetNuke (DNN) 的两种主要版本:Community 和 Professional。通过对比两者的功能和附加组件,帮助用户选择最适合其需求的版本。 ... [详细]
  • 本文探讨了领域驱动设计(DDD)的核心概念、应用场景及其实现方式,详细介绍了其在企业级软件开发中的优势和挑战。通过对比事务脚本与领域模型,展示了DDD如何提升系统的可维护性和扩展性。 ... [详细]
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社区 版权所有