Original: Http://blogs.msdn.com/b/henrikn/archive/2012/08/07/httpclient-httpclienthandler-and-httpwebrequesthandler.aspx
In both previous blogs I describe how to use HttpClient as well as how to use the Httpmessagehandler pipeline. What we haven ' t explicitly are showing when and how to use HttpClient, Httpclienthandler, Andwebrequesthandler. This is the purpose of this blog.
This article describes how to use HttpClient, httpclienthandler, andwebrequesthandler.
The first thing to remember is, HttpClient uses the Httpmessagehandler pipeline for sending and receiving requests. The default handler implementations (Httpclienthandler and Webrequesthandler) both sit on top ofhttpwebrequest which have a Lot of properties for controlling what 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 is rarely used.
The first thing to remember is that HttpClient uses the Httpmessagehandler pipeline to send and receive requests. The default Hanlder implementation (Httpclienthandler and Webrequesthandler) is located httpwebrequest,httpwebrequest there is a need for blood transfusions to control requests and responses. However, to keep it simple, httpclient does not expose all of these attributes-which makes it awkward, because there are many properties that are seldom used.
If you need to access these properties then there is the ways of doing it:use either Httpclienthandler or Webrequesthand Ler. Both is httpmessagehandlers hooked in as part of the Httpmessagehandler pipeline. Below we'll describe when and what to use these handlers, how they differ, as well as how to combine them with your own H Andlers.
Can find this code for this sample in the Aspnet.codeplex.com code repository and there is instructions here for how To use the samples.
HttpClient
The default HttpClient is the simplest on which you can start sending requests. A single HttpClient can is used to send as many HTTP requests as you want concurrently so in many scenarios you can just C Reate one HttpClient and then use the, for all your requests.
HttpClient have a few properties that is commonly used and which can set up until the point where you start S Ending 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 is 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 for before the request times out. |
Here's an example of what 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 =NewHttpClient (); 3: Client. Timeout = Timespan.fromseconds (Ten); 4: 5://Issue a request 6: Client. Getasync (_address). ContinueWith (7: Gettask =8: { 9:if(gettask.iscanceled)Ten: { One: Console.WriteLine ("Request was canceled"); A: } -:Else if(gettask.isfaulted) -: { the: Console.WriteLine ("Request failed: {0}", gettask.exception); -: } -:Else -: { +: httpresponsemessage response =Gettask.result; -: Console.WriteLine ("Request completed with status code {0}", Response. StatusCode); +: } A: });
If you had additional handlers which you want to wire up as well then the simplest it's to use the Httpclientfactory cl The. Here's a example wiring up 3 custom message handlers:
If there are other handler trying to string them up, the simplest way is to use the Httpclientfactory class.
1://Create an HttpClient and add message handlers for the client 2: HttpClient client =Httpclientfactory.create (3:NewSamplehandler ("Client A",2), 4:NewSamplehandler ("Client B",4), 5:NewSamplehandler ("Client C",6));
Httpclienthandler
Httpclienthandler is an httpmessagehandler with a common set of properties that works across most versions of the HTTPWEBR Equest API. The the default handler and so are what if you get the default constructor. However, in order to actually get access to the various properties (see below) you have to explicitly create it and then P it to HttpClient.
Httpclienthandler is the default handler and is what you get when you use the HttpClient default constructor. However, if you want to actually access its various properties, you must show it to create it and then pass it on to 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 is associated with this handler. |
Cookiecontainer |
Gets or sets the cookie container used to store server for 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 maxautomatic Redirectionsproperties. |
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 is sent with requests by the handler. |
UseProxy |
Gets or sets a value that indicates whether the handler uses a proxies for requests. |
Here's an example of what to create an Httpclienthandler, set a property, and pass it to HttpClient:
1 // Create Httpclienthandler and set useDefaultCredentials Property 2 New Httpclienthandler (); 3 true ; 4 : 5 // Create an HttpClient using the Httpclienthandler 6 New HttpClient (ClientHandler);
Like above, can combine your Httpclienthandler instance with other custom handlers, here's what's it looks like:
1://Create Httpclienthandler and set useDefaultCredentials property 2: Httpclienthandler ClientHandler =NewHttpclienthandler (); 3: Clienthandler.usedefaultcredentials =true; 4: 5://Create an HttpClient and add message handlers for the client 6: HttpClient client =Httpclientfactory.create (7: ClientHandler,8:NewSamplehandler ("Client A",2), 9:NewSamplehandler ("Client B",4), Ten:NewSamplehandler ("Client C",6));
Webrequesthandler
Webrequesthandler derives from Httpclienthandler but adds properties the generally only is available on full. NET. The Webrequesthandler is not included in the System.Net.Http DLL and rather in System.Net.Http.WebRequest DLL so You have to explicitly include the as a reference in order to see it. Otherwise it won ' t show up.
Webrequesthandler inherits from Httpclienthandler and adds properties, usually in full. NET in order to use. Webrequesthandler is not included in the System.Net.Http DLL, it is in the System.Net.Http.WebRequest DLL , a separate reference is required if you want to use it.
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 is associated with this request. |
Continuetimeout |
Gets or sets the amount of time, in milliseconds, the application would wait for 100-continue from the server before upload ing 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 if 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 what 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 =NewWebrequesthandler (); 3: Webrequesthandler.usedefaultcredentials =true; 4: webrequesthandler.allowpipelining =true; 5: 6://Create an HttpClient using the Webrequesthandler 7: HttpClient client =NewHttpClient (Webrequesthandler);
Again, can combine the Webrequesthandler with your own handlers as Well–here's what's it looks like:
Webrequesthandler can also be combined with other handler.
1://Create Webrequesthandler and set useDefaultCredentials and allowpipelining (for HTTP) Properties 2: Webrequesthandler Webrequesthandler =NewWebrequesthandler (); 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:NewSamplehandler ("Client A",2), Ten:NewSamplehandler ("Client B",4), One:NewSamplehandler ("Client C",6));
HttpClient, Httpclienthandler, and Webrequesthandler explained