HttpClient, HttpClientHandler, and WebRequestHandler介绍
注:本文为个人学习摘录,原文地址:https://blogs.msdn.microsoft.com/henrikn/2012/08/07/httpclient-httpclienthandler-and-webrequesthandler-explained/
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 HttpClient, HttpClientHandler, and WebRequestHandler. This is the purpose of this blog.
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 of HttpWebRequest 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.
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:
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:
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.
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 theAllowAutoRedirect and MaxAutomaticRedirections properties. |
UseCookies | Gets or sets a value that indicates whether the handler uses the CookieContainer 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.
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:
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));
Have fun!
Henrik
HttpClient, HttpClientHandler, and WebRequestHandler介绍的更多相关文章
- HttpClient, HttpClientHandler, and WebRequestHandler Explained
原文地址 https://blogs.msdn.microsoft.com/henrikn/2012/08/07/httpclient-httpclienthandler-and-webrequest ...
- 理解并使用.NET 4.5中的HttpClient
HttpClient介绍 HttpClient是.NET4.5引入的一个HTTP客户端库,其命名空间为System.Net.Http..NET 4.5之前我们可能使用WebClient和HttpWeb ...
- 理解并使用.NET 4.5中的HttpClient(转)
原文地址:http://www.cnblogs.com/wywnet/p/httpclient.html HttpClient介绍HttpClient是.NET4.5引入的一个HTTP客户端库,其命名 ...
- httpclient cer
X509Certificate2 cer = new X509Certificate2(@"path", "********", X509KeyStorageF ...
- HttpClient相关
HTTPClient的主页是http://jakarta.apache.org/commons/httpclient/,你可以在这里得到关于HttpClient更加详细的信息 HttpClient入门 ...
- HttpClient(4.3.3)实例讲解
HttpClient的作用强大,真的是十分强大. 本实例是基于v4.3.3写的,,作用是模拟登陆后进行上下班打卡,,,使用htmlparser进行解析返回的html文件 关于HttpClient的一些 ...
- 重新想象 Windows 8.1 Store Apps (88) - 通信的新特性: 新的 HttpClient
[源码下载] 重新想象 Windows 8.1 Store Apps (88) - 通信的新特性: 新的 HttpClient 作者:webabcd 介绍重新想象 Windows 8.1 Store ...
- .Net HttpClient 模拟登录微信公众平台发送消息
1.模拟登录 public WeiXinRetInfo ExecLogin(string name, string pass) { CookieContainer cc = new CookieCon ...
- 使用HttpClient发送GET请求
HttpRequestMessage http_req_msg = new HttpRequestMessage(); http_req_msg.Method = HttpMethod.Get; ht ...
随机推荐
- R和python连接SQL sever 数据库操作
在R的使用中,为了方便提取数据, 我们经常要进行数据库进行操作,接下来我们尝试使用R进行连接数据. 这里我们使用R中的RODBC进行操作, 首先,我们需要先配置ODBC资源管理器 通过任务管理器或者w ...
- JAVA-代理学习一之JDK实现
代理的实现依赖于反射,建议不太懂反射的童鞋先看看反射相关的知识点. 代理可以理解为对实际调用方法的一种能力的加强. 代理分为静态代理和动态代理: <1> 静态代理示例 接口MyInterf ...
- Maven之(五)Maven仓库
本地仓库 Maven一个很突出的功能就是jar包管理,一旦工程需要依赖哪些jar包,只需要在Maven的pom.xml配置一下,该jar包就会自动引入工程目录.初次听来会觉得很神奇,下面我们来探究一下 ...
- 继承,多态,集合,面向对象,XML文件解析,TreeView动态加载综合练习----->网络电视精灵项目练习、分析
网络电视精灵 项目运行状态如图: 项目完成后的类: 首先,将程序分为二部分进行: 一:TreeView节点内容的设计及编写: 1.1遍写XML文件:管理(FullChannels.xml),A类电视台 ...
- linux下正确安装jsoncpp
要安装jsoncpp,首先要下载好scons,再去安装jsoncpp scons下载地址:wget http://prdownloads.sourceforge.NET/scons/scons-2.2 ...
- centos搭建svn服务器
1.在centos6.5上面搭建svn服务器,安装svn服务器:yum install subversion 2.在任意目录下创建仓库目录,这里放在/data/mypros目录下 3.执行命令:svn ...
- Leetcode easy
1. Two Sum Given an array of integers, return indices of the two numbers such that they add up to a ...
- 诡异的数学,数字问题 - leetcode
134. Gas Station 那么这题包含两个问题: 1. 能否在环上绕一圈? 2. 如果能,这个起点在哪里? 第一个问题,很简单,我对diff数组做个加和就好了,leftGas = ∑diff[ ...
- jquery 自动触发事件 trigger
trigger() 栗子: 需求:我们在做二级联动的时候往往会遇到这样的需求,后台管理端页面加载完成后显示用户的省份,城市,并且可以对用户的省份,城市信息可以修改 如果只是简单的显示 你完全可以直接放 ...
- JS 获取网页的宽高
网页可见区域宽: document.body.clientWidth网页可见区域高: document.body.clientHeight网页可见区域宽: document.body.offsetWi ...