HttpClient, HttpClientHandler, and WebRequestHandler Explained
原文地址 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 the AllowAutoRedirect 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!
HenrikHttpClient, HttpClientHandler, and WebRequestHandler Explained
HttpClient, HttpClientHandler, and WebRequestHandler Explained的更多相关文章
- HttpClient, HttpClientHandler, and WebRequestHandler介绍
注:本文为个人学习摘录,原文地址:https://blogs.msdn.microsoft.com/henrikn/2012/08/07/httpclient-httpclienthandler-an ...
- 理解并使用.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 ...
- .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 ...
- .net 中HttpClient 携带cookie传输
CookieContainer cookieContainer = new CookieContainer(); Cookie cookie = new Cookie("username&q ...
- HttpClient Received an unexpected EOF or 0 bytes from the transport stream
请求https链接时报错,奇怪的是pc1正常,pc2异常 Unhandled Exception: System.AggregateException: One or more errors occu ...
- .Net Core HttpClient 忽略https证书提醒
在测试中经常会遇到请求一些https的url,但又没有本地证书,这时候可以用下面的方法忽略警告 var httpclientHandler = new HttpClientHandler(); htt ...
随机推荐
- 代码覆盖工具(gcov、lcov)的使用
一.安装 gcov:是随gcc一起发布的,并不需要独立安装:lcov:其他博客说是随ltp发布的,结果下载下ltp之后编译了10多分钟,最后也没见lcov,最后到sourceforge下载了lcov单 ...
- 搭建一套自己实用的.net架构(2)【日志模块-log4net】
先谈谈简单的模块,日志.在系统中日志模块是必须的,什么系统日志,操作日志,调试日志.这里用的是log4net. 对log4net还不熟悉的小伙伴们赶快去搜索基础教程哦, 我这里就不温故了. 那么有人要 ...
- css设置select高度(IE,FF,Chrome)[转]
大家都知道select是无法设置高度和边框颜色等等的在ie67下面,其他的都是可以的,所以有时候为了在所有的浏览器下显示都一致,就使用了 js的模拟,这个是大家经常碰到的,js不光要模拟外观还有模拟事 ...
- 微博公众平台(二)-- Token验证代码
Token,验证逻辑:1.将Token.timestamp.nonce放入数组 2.将数组从小到大排列 3.将数组按顺序拼装成一个字符串 4.对生成的字符串进行SHA1加密 5.将密文转换为小写 6. ...
- socketAPI:一个最简单的服务器和对应的客户端C语言的实现
基于linux,该实例实现了服务端传了一个hello world给客户端.socket()创建socketbind()绑定socket到IP地址和端口listen()服务器监听客户端的连接connec ...
- 通过接口实现JAVA和.NET互调用-JNInterface
使用C#编程多年,也十分感激微软在语言架构.语法糖.编辑器等方面给自己带来的便利.但因为最近工作中有接触到JAVA,渐渐地发现的确像大家说的那样,JAVA的生态很好,要找点什么几乎都有现成的,于是自然 ...
- Ubuntu 16.04 LTS设置国内更新源
ubuntu一般多用于开发环境,centos/redhat多用于企业环境.suse多用于银行金融行业!!! 01.ubuntu源地址 /etc/apt/sources.list 02.更新缓存资源索引 ...
- 使用对话框 —— Dialog
对话框就是一般的弹出窗口,主要用来提示用户,和用户交互. 创建Activity对话框 使用Activity模拟对话框.这个比较简单,主要是使用Activity自带的Dialog主题. 创建 ...
- 修改httpd默认端口号
Tomcat: vim /etc/httpd/conf/httpd.conf//别忘了service httpd restart Nginx: vim /etc/nginx/nginx.conf//完 ...
- mysql忘记root密码解决办法
最近项目中的数据库我放在了服务器上,但是今天突然不能用了,进入服务器查看,果然是数据库不能进去了,所以今天来分享一个mysql忘记root密码的解决方案: 1.让mysql不载入权限表,命令:mysq ...