HttpClient, HttpClientHandler, and WebRequestHandler Explained

原文:http://blogs.msdn.com/b/henrikn/archive/2012/08/07/httpclient-httpclienthandler-and-httpwebrequesthandler.aspx

In two previous blogs I describe how to use HttpClient as well as how to use the HttpMessageHandler pipeline. What we haven’t done explicitly is showing when and how to use HttpClientHttpClientHandler, andWebRequestHandler. This is the purpose of this blog.

本文介绍如何使用 HttpClientHttpClientHandler, andWebRequestHandler.

The first thing to remember is that HttpClient uses the HttpMessageHandler pipeline for sending and receiving requests. The default handler implementations (HttpClientHandler and WebRequestHandler) both sit on top ofHttpWebRequest which has a lot of properties for controlling how to deal with requests and responses. However, in order to stay simple, HttpClient doesn’t expose all these properties up front – it would make it unwieldy and show a lot of things that are rarely used.

首先要记住的是HttpClient使用HttpMessageHandler管道来发送和接收请求。缺省的hanlder实现(HttpClientHandler and WebRequestHandler)都位于HttpWebRequestHttpWebRequest有需要输血用于控制请求和响应。然而,为了保持简单,HttpClient没有暴露出所有这些属性--这会让它显得笨拙,因为有很多属性很少用到。

If you need to access these properties then there are two ways of doing it: use either HttpClientHandler or WebRequestHandler. Both are HttpMessageHandlers hooked in as part of the HttpMessageHandler pipeline. Below we will describe when and how to use these handlers, how they differ, as well as how to combine them with your own handlers.

You can find this code for this sample in the aspnet.codeplex.com code repository and there are instructions here for how to use the samples.

HttpClient

The default HttpClient is the simplest way in which you can start sending requests. A single HttpClient can be used to send as many HTTP requests as you want concurrently so in many scenarios you can just create one HttpClient and then use that for all your requests.

HttpClient has a few properties that are commonly used and which you can set up until the point where you start sending requests, namely:

The properties exposed by HttpClient directly
Name Description
BaseAddress Gets or sets the base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests.
DefaultRequestHeaders Gets the headers which should be sent with each request.
MaxResponseContentBufferSize Gets or sets the maximum number of bytes to buffer when reading the response content.
Timeout Gets or sets the number of milliseconds to wait before the request times out.

Here’s an example of how to create a simple HttpClient and issue a request while setting the timeout for all requests:

 1: // Create an HttpClient and set the timeout for requests
   2: HttpClient client = new HttpClient();
   3: client.Timeout = TimeSpan.FromSeconds(10);
   4:
   5: // Issue a request
   6: client.GetAsync(_address).ContinueWith(
   7:     getTask =>
   8:     {
   9:         if (getTask.IsCanceled)
  10:         {
  11:             Console.WriteLine("Request was canceled");
  12:         }
  13:         else if (getTask.IsFaulted)
  14:         {
  15:             Console.WriteLine("Request failed: {0}", getTask.Exception);
  16:         }
  17:         else
  18:         {
  19:             HttpResponseMessage response = getTask.Result;
  20:             Console.WriteLine("Request completed with status code {0}", response.StatusCode);
  21:         }
  22:     });

If you have additional handlers which you want to wire up as well then the simplest way is to use the HttpClientFactory class. Here’s an example wiring up 3 custom message handlers:

如果有其它的handler想把它们串接起来,最简单的方法是使用HttpClientFactory 类。

   1: // Create an HttpClient and add message handlers for the client
   2: HttpClient client = HttpClientFactory.Create(
   3:     new SampleHandler("Client A", 2),
   4:     new SampleHandler("Client B", 4),
   5:     new SampleHandler("Client C", 6));

HttpClientHandler

HttpClientHandler is an HttpMessageHandler with a common set of properties that works across most versions of the HttpWebRequest API. This is the default handler and so is what you get if you use the default constructor. However, in order to actually get access to the various properties (see below) you have to explicitly create it and then pass it to HttpClient.

HttpClientHandler 是缺省的handler,也是你用Httpclient缺省构造函数时得到的。然而,如果要实际访问它的各种属性,你必须显示创建它,然后传给HttpClient。

List of Properties for HttpClientHandler
Name Description
AllowAutoRedirect Gets or sets a value that indicates whether the handler should follow redirection responses.
AutomaticDecompression Gets or sets the type of decompression method used by the handler for automatic decompression of the HTTP content response.
ClientCertificateOptions Gets or sets the collection of security certificates that are associated with this handler.
CookieContainer Gets or sets the cookie container used to store server cookies by the handler.
Credentials Gets or sets authentication information used by this handler.
MaxAutomaticRedirections Gets or sets the maximum number of redirects that the handler follows.
MaxRequestContentBufferSize Gets or sets the maximum request content buffer size used by the handler.
PreAuthenticate Gets or sets a value that indicates whether the handler sends an Authorization header with the request.
Proxy Gets or sets proxy information used by the handler.
SupportsAutomaticDecompression Gets a value that indicates whether the handler supports automatic response content decompression.
SupportsProxy Gets a value that indicates whether the handler supports proxy settings.
SupportsRedirectConfiguration Gets a value that indicates whether the handler supports configuration settings for the AllowAutoRedirect and MaxAutomaticRedirectionsproperties.
UseCookies Gets or sets a value that indicates whether the handler uses theCookieContainer property to store server cookies and uses these cookies when sending requests.
UseDefaultCredentials Gets or sets a value that controls whether default credentials are sent with requests by the handler.
UseProxy Gets or sets a value that indicates whether the handler uses a proxy for requests.

Here’s an example of how to create an HttpClientHandler,  set a property, and pass it to HttpClient:

  1: // Create HttpClientHandler and set UseDefaultCredentials property
   2: HttpClientHandler clientHandler = new HttpClientHandler();
   3: clientHandler.UseDefaultCredentials = true;
   4:
   5: // Create an HttpClient using the HttpClientHandler
   6: HttpClient client = new HttpClient(clientHandler);

Like above, you can combine your HttpClientHandler instance with other custom handlers, here’s what it looks like:

  1: // Create HttpClientHandler and set UseDefaultCredentials property
   2: HttpClientHandler clientHandler = new HttpClientHandler();
   3: clientHandler.UseDefaultCredentials = true;
   4:
   5: // Create an HttpClient and add message handlers for the client
   6: HttpClient client = HttpClientFactory.Create(
   7:     clientHandler,
   8:     new SampleHandler("Client A", 2),
   9:     new SampleHandler("Client B", 4),
  10:     new SampleHandler("Client C", 6));

WebRequestHandler

WebRequestHandler derives from HttpClientHandler but adds properties that generally only are available on full .NET. The WebRequestHandler is not included in the System.Net.Http DLL but rather in System.Net.Http.WebRequest DLL so you have to explicitly include that as a reference in order to see it. Otherwise it won’t show up.

WebRequestHandler 从HttpClientHandler 继承,并添加了属性,通常在完整的.NET中才能使用。WebRequestHandler 不包含在System.Net.Http DLL中,它在System.Net.Http.WebRequest DLL ,如果要使用它,需要单独引用。

List of Properties for WebRequestHandler in addition to those of HttpClientHandler
Name Description
AllowPipelining Gets or sets a value that indicates whether to pipeline the request to the Internet resource.
AuthenticationLevel Gets or sets a value indicating the level of authentication and impersonation used for this request.
CachePolicy Gets or sets the cache policy for this request.
ClientCertificates Gets or sets the collection of security certificates that are associated with this request.
ContinueTimeout Gets or sets the amount of time, in milliseconds, the application will wait for 100-continue from the server before uploading data.
ImpersonationLevel Gets or sets the impersonation level for the current request.
MaxResponseHeadersLength Gets or sets the maximum allowed length of the response headers.
ReadWriteTimeout Gets or sets a time-out in milliseconds when writing a request to or reading a response from a server.
ServerCertificateValidationCallback Gets or sets a callback for verifying the remote Secure Sockets Layer (SSL) certificate used for authentication.
UnsafeAuthenticatedConnectionSharing Gets or sets a value that indicates whether to allow high-speed NTLM-authenticated connection sharing.

Here’s an example of how to create an WebRequestHandler, set a property, and pass it to HttpClient:

  1: // Create WebRequestHandler and set UseDefaultCredentials and AllowPipelining (for HTTP) properties
   2: WebRequestHandler webRequestHandler = new WebRequestHandler();
   3: webRequestHandler.UseDefaultCredentials = true;
   4: webRequestHandler.AllowPipelining = true;
   5:
   6: // Create an HttpClient using the WebRequestHandler
   7: HttpClient client = new HttpClient(webRequestHandler);

Again, you can combine the WebRequestHandler with your own handlers as well – here’s what it looks like:

也可以将WebRequestHandler 与其它handler组合起来使用。

  1: // Create WebRequestHandler and set UseDefaultCredentials and AllowPipelining (for HTTP) properties
   2: WebRequestHandler webRequestHandler = new WebRequestHandler();
   3: webRequestHandler.UseDefaultCredentials = true;
   4: webRequestHandler.AllowPipelining = true;
   5:
   6: // Create an HttpClient and add message handlers for the client
   7: HttpClient client = HttpClientFactory.Create(
   8:     webRequestHandler,
   9:     new SampleHandler("Client A", 2),
  10:     new SampleHandler("Client B", 4),
  11:     new SampleHandler("Client C", 6));
时间: 2024-10-21 21:37:24

HttpClient, HttpClientHandler, and WebRequestHandler Explained的相关文章

理解并使用.NET 4.5中的HttpClient(转)

原文地址:http://www.cnblogs.com/wywnet/p/httpclient.html HttpClient介绍HttpClient是.NET4.5引入的一个HTTP客户端库,其命名空间为System.Net.Http..NET 4.5之前我们可能使用WebClient和HttpWebRequest来达到相同目的.但是有几点值得关注: 可以使用单个HttpClient实例发任意数目的请求一个HttpClient实例不会跟某个HTTP服务器或主机绑定,也就是说我们可以用一个实例同

使用HttpClient发送GET请求

HttpRequestMessage http_req_msg = new HttpRequestMessage(); http_req_msg.Method = HttpMethod.Get; http_req_msg.Headers.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); http_req_msg.RequestUr

.net 中HttpClient 携带cookie传输

CookieContainer cookieContainer = new CookieContainer(); Cookie cookie = new Cookie("username", "username"); cookie.Domain = Request.Url.Host; cookieContainer.Add(cookie); // 加入Cookie HttpClientHandler httpClientHandler = new HttpClien

HttpClient Received an unexpected EOF or 0 bytes from the transport stream

请求https链接时报错,奇怪的是pc1正常,pc2异常 Unhandled Exception: System.AggregateException: One or more errors occurred. ( Received an unexpected EOF or 0 bytes from the transport stream.) ---> System.IO.IOException: Received an unexpected EOF or 0 bytes from the t

NetCore HttpClient The SSL connection could not be established, see inner exception

之前遇到一个问题 https://www.cnblogs.com/leoxjy/p/10201046.html 在centos 7.x  HttpClient访问会出问题  The SSL connection could not be established, see inner exception 最后彻底解决是进入容器docker 那么 最近又FQ搜到一个解决方案 可以systemctl 运行的时候也不会 SSL 上代码 var httpClientHandler = new HttpCl

.net core使用HttpClient发送代理请求_程序内抓包_Fiddler抓包

原文:.net core使用HttpClient发送代理请求_程序内抓包_Fiddler抓包 前言:  通过Fiddler抓取浏览器请求数据,相信大家已经都会用了,我们知道Fiddler是通过在本机计算器添加一个默认的代理服务器来实现的抓包数据的,端口号为:8888. 其实当我们打开Fiddler的设置也可以看到: 然后查看本地计算器的网络代理设置: 基于上面的原理,Fiddler就实现了经过本机计算器请求的数据抓包了... 那么,我们通过C#代码,在.net Core中使用HttpClient

http client transfer

背景 在平时工作中我偶尔会写一些脚本监控HTTP接口的健康状况,基本上都是发送HTTP GET或HTTP POST请求,然后检测响应内容.但一直用的是WebClient和HttpWebRequest,虽然用它们也能进行异步请求(可参考我分享的代码:C#异步GET的3个例子),但总感觉那样用起来不太自然.网上搜索后发现.NET 4.5引入的HttpClient库能够完成异步HTTP请求.于是结合多方资料总结下HttpClient的特性和使用.本文属于阅读笔记性质博客! 准备工作     在Visu

Asp.Net Web API 2第三课——.NET客户端调用Web API

Asp.Net Web API 导航 Asp.Net Web API第一课——入门http://www.cnblogs.com/aehyok/p/3432158.html Asp.Net Web API第二课——CRUD操作http://www.cnblogs.com/aehyok/p/3434578.html 前言 本教程演示从一个控制台应用程序,使用HttpClient调用Web API.我们也将使用上一个教程中建立的Web API.你可以直接在http://www.cnblogs.com/

httpclient与webapi

System.Net.Http 是微软推出的最新的 HTTP 应用程序的编程接口, 微软称之为“现代化的 HTTP 编程接口”, 主要提供如下内容: 1. 用户通过 HTTP 使用现代化的 Web Service 的客户端组件: 2. 能够同时在客户端与服务端同时使用的 HTTP 组件(比如处理 HTTP 标头和消息), 为客户端和服务端提供一致的编程模型. 命名空间  System.Net.Http  以及  System.Net.Http.Headers  提供了如下内容: 1.  Http