HTTP client Transfer

Source: Internet
Author: User
Tags http post oauth sha1

Background

I occasionally write scripts to monitor the health of the HTTP interface, basically sending an HTTP GET or HTTP POST request, and then detecting the response content. But always using WebClient and HttpWebRequest, although they can also be used to make asynchronous requests (see the code I shared: 3 examples of C # async get), but it feels like it's not natural to use it. After searching online, we found that the HttpClient library introduced by. NET 4.5 is capable of completing asynchronous HTTP requests. So combined with multi-data to summarize the characteristics and use of httpclient. This article belongs to the nature of reading notes blog !

Preparatory work

Create a new console app in Visual Studio 2012, and then add the to System. Net and System.Net.Http assemblies .

HttpClient Introduction

HttpClient is a. NET4.5 introduced an Http client library whose namespace is System.Net.Http. Net 4.5 Before we might use WebClient and HttpWebRequest for the same purpose. But there are a few things to watch out for:

    • You can use a single httpclient instance to send any number of requests
    • An httpclient instance is not bound to an HTTP server or host, which means that we can use an instance to send www.a.com and www.b.com requests simultaneously
    • can inherit httpclient to achieve custom purpose
    • HttpClient leverages the latest task-oriented mode, making it easy to process asynchronous requests

Asynchronous HTTP GET

Here is an example of using HttpClient for HTTP GET request data:

using system;using System.net.http;namespace Httpclientproject{class Httpclientdemo {Private Const string Uri = "Http://api.worldbank.org/countries?form        At=json ";            static void Main (string[] args) {HttpClient HttpClient = new HttpClient (); Creates an asynchronous get request to continue processing Httpclient.getasync (Uri) when the request returns. ContinueWith (Requesttask) = {Httpresponsemessage response = Reques                    Ttask.result; Confirm the response is successful, or throw an exception response.                      Ensuresuccessstatuscode (); The asynchronous read response is a string response. Content.readasstringasync ().                ContinueWith (Readtask) = Console.WriteLine (Readtask.result));            });            Console.WriteLine ("Hit Enter to exit ...");        Console.ReadLine (); }    }}

When the code runs, it prints "hit Enter to exit ..." before outputting the request response, because the Getasync (string requesturi) Async method, which returns the Taskprogramming , you can refer to the fourth section of the four methods of JavaScript asynchronous programming and the deferred object of jquery in detail. So we can rewrite the above code with the async, await keyword supported after. NET 4.5, and still have asynchrony:

Using system;using system.net.http;namespace httpclientproject{    class Httpclientdemo    {        Private const String Uri = "Http://api.worldbank.org/countries?format=json";        static async void Run ()        {            HttpClient HttpClient = new HttpClient ();            Creates an asynchronous get request to continue processing when the request returns (Continue-with mode)            httpresponsemessage response = await httpclient.getasync (Uri);            Response. Ensuresuccessstatuscode ();            String resultstr = await response. Content.readasstringasync ();            Console.WriteLine (RESULTSTR);        }        static void Main (string[] args)        {            Run ();            Console.WriteLine ("Hit Enter to exit ...");            Console.ReadLine ();}}}    

Notice what happens if we get httpresponsemessage in the following way?

Httpresponsemessage response = Httpclient.getasync (URL). Result;

The consequence is that access to the result property is a blocking program that continues to run, thus losing the power of asynchronous programming. Similar to:

String resultstr = Response. Content.readasstringasync ();

will also cause the program to be blocked.

Asynchronous HTTP POST

I used to write a HttpWebRequest automatically login to open source China code (see C # automatic Login open source China), on this basis I use the HttpClient Postasync method to rewrite the following:

Using system;using system.collections.generic;using system.linq;using system.net;using System.Net.Http;using System.web.security;namespace asycloginoschina{public class Oschinalogin {//<summary>///settings Request header information///</summary>//<param name= "client" ></param> public static void Setreques Theader (HttpClient client) {client.            Defaultrequestheaders.add ("Host", "www.oschina.net"); Client.            Defaultrequestheaders.add ("Method", "Post"); Client.   Defaultrequestheaders.add ("KeepAlive", "false"); The HTTP keepalive is set to False to prevent HTTP connections from keeping the client. Defaultrequestheaders.add ("useragent", "mozilla/5.0" (Windows NT 6.1; WOW64) applewebkit/537.11 (khtml, like Gecko)Chrome/23.0.1271.95 safari/537.11 "); }//MD5 or SHA1 encrypt public static string Encryptpassword (String pwdstr, String pwdformat) {St            Ring Encryptpassword = null; if ("SHA1"). Equals (Pwdformat.toupper ())) {Encryptpassword = Formsauthentication.hashpasswordforstoringincon            Figfile (Pwdstr, "SHA1"); } else if ("MD5". Equals (Pwdformat.toupper ())) {Encryptpassword = Formsauthentication.hashpasswordforstoringincon            Figfile (Pwdstr, "MD5");            } else {encryptpassword = Pwdstr;        } return Encryptpassword; }///<summary>//Oschina Login function///</summary>//<param name= "email" ></ param>//<param name= "pwd" ></param> public static void Loginoschina (string email, string pw           d) {HttpClient HttpClient = new HttpClient (); Set the request header information HttpClient.DefaultRequestHeaders.Add ("Host", "www.oschina.net");            HTTPCLIENT.DEFAULTREQUESTHEADERS.ADD ("Method", "Post");   HTTPCLIENT.DEFAULTREQUESTHEADERS.ADD ("KeepAlive", "false"); The HTTP keepalive is set to False to prevent the HTTP connection from remaining httpClient.DefaultRequestHeaders.Add ("useragent", "MOZILLA/5 .0 (Windows NT 6.1;            WOW64) applewebkit/537.11 (khtml, like Gecko) chrome/23.0.1271.95 safari/537.11 ");            Construct Post parameters httpcontent postcontent = new Formurlencodedcontent (new dictionary<string, string> ()            {"Email", email}, {"Pwd", Encryptpassword (pwd, "SHA1")}); HttpClient. Postasync ("Http://www.oschina.net/action/user/hash_login", postcontent). ContinueWith ((posttask) = {Httpresponsemessage Response = Post                       Task.result;             Confirm the response succeeds or throw an exception          Response.                       Ensuresuccessstatuscode (); The asynchronous read response is a string response. Content.readasstringasync ().                       ContinueWith ((Readtask) = Console.WriteLine ("Response to Web content:" + readtask.result)); Console.WriteLine ("The response is successful:" + response.)                       Issuccessstatuscode);                       Console.WriteLine ("Response header information as follows: \ n"); var headers = Response.                       Headers; foreach (var header in headers) {Console.WriteLine ("{0}: {1}", header.) Key, String. Join ("", header.                       Value.tolist ()));        }                   }               );            } public static void Main (string[] args) {Loginoschina ("Your Mailbox", "Your password");        Console.ReadLine (); }    }}

The code is very simple, not much to say, as long as the above main function of the mailbox, password information to replace your own Oschina login information. The request header information is set by the Httpclient.defaultrequestheaders property above, or it can be set by the Postcontent.header property. The above does not show how to set cookies, and some post requests may need to carry cookies, then what should be done? This is the time to use Httpclienthandler (see the next section for more information about it), as follows:

Cookiecontainer Cookiecontainer = new Cookiecontainer () Cookiecontainer.add (New Cookie ("Test", "0"));   Add Cookiehttpclienthandler Httpclienthandler = new Httpclienthandler () {   Cookiecontainer = Cookiecontainer,   AllowAutoRedirect = True,   usecookies = true}; HttpClient HttpClient = new HttpClient (Httpclienthandler);

Then use HttpClient as before. For information on how to access the cookie in the request and set the cookie in the ASP, you can refer to: ASP.

Other HTTP operations, such as put and delete, are implemented by HttpClient's Putasync and Deleteasync, which are basically the same as above.

Error handling

By default, if an HTTP request fails, no exception is thrown, but we can detect the success of the request by returning the StatusCode property of the Httpresponsemessage object, such as the following:

Httpresponsemessage response = posttask.result;if (response. StatusCode = = Httpstatuscode.ok) {   //...}

or through the Issuccessstatuscode property of Httpresponsemessage to detect:

Httpresponsemessage response = posttask.result;if (response. Issuccessstatuscode) {   //...}

Or if you prefer to handle request failures in an unusual way, you can use the following code:

try{    httpresponsemessage response = Posttask.result;    Response. Ensuresuccessstatuscode ();} catch (Httprequestexception e) {    //...}

The Ensuresuccessstatuscode () method of the Httpresponsemessage object throws an exception when the HTTP response does not return a success status code (2XX), and the exception can be caught by the catch.

Httpmessagehandler Pipeline

On the ASP. Delegating handler mode is typically used to process HTTP requests and return HTTP responses: In general, multiple message processors are concatenated together to form a message processor chain (Httpmessagehandler Pipeline). The first message processor handles the request and hands the request to the next message handler ... Finally, at some point, a message handler returns a response object after processing the request and then returns up the message processor chain, as shown in: (this blog is primarily related to httpclient, so if you want to learn more about ASP. NET Web API Service-side message processors, refer to: HTTP Message handlers)

HttpClient also uses the message processor to process requests, the default message processor is Httpclienthandler (the above asynchronous HTTP POST is used), we can also customize the client message processor, the message processor chain processes the request and returns the response process such as:

If we want to customize a client message handler ourselves, we need to inherit Delegatinghandler and rewrite the following method:

Task

For example, the following customizes a client message handler to record an HTTP error code:

Class logginghandler:delegatinghandler{    StreamWriter _writer;    Public Logginghandler (Stream stream)    {        _writer = new StreamWriter (stream);    }    protected override Async task

Then we need to bind the custom message processor to the HttpClient object using the following code:

HttpClient client = httpclientfactory.create (new Logginghandler (), New Handler2 (), New Handler3 ());

The above custom message processor only intercepts the HTTP response, and if we want to intercept processing HTTP requests and intercept the HTTP response, what do we do? As follows:

public class myhandler:delegatinghandler{   private string _name;     Public MyHandler (string name)   {      _name = name;   }     Intercept request and response   protected override task

The above 1 intercept requests and process them. Another example on the MSDN blog is the use of client-side message handlers to implement OAuth validation, with the following: extending HttpClient with OAuth to Access Twitter

Webrequesthandler

This article has been written long enough, but I've always wanted to know something a little bit more about it at once, and I'm going to add this to the other class-webrequesthandler that was not previously involved.

Webrequesthandler inherits from Httpclienthandler, but is included in the System.Net.Http.WebRequest assembly. Some of its properties are shown in the following table:

Property Description Allowpipelining
Gets or sets whether the request is allowed to be pipeline AuthenticationLevel
Gets or sets the authentication level CachePolicy
Gets or sets the cache policy for this request clientcertificates
Gets or sets the security certificate set for this request Continuetimeout
When uploading data, the client must wait for the server to return 100-continue, which sets the time-out to return 100-continue Maxresponseheaderslength
Gets or sets the maximum length of the response header Readwritetimeout
Gets or sets the time-out for a write request or read response Servercertificatevalidationcallback
Gets or sets the callback function after SSL verification is complete
A simple example of using Webrequesthandler is as follows:

Webrequesthandler Webrequesthandler = new Webrequesthandler (); webrequesthandler.usedefaultcredentials = true; webrequesthandler.allowpipelining = true;//Create an HttpClient using the Webrequesthandler (); HttpClient client = new HttpClient (Webrequesthandler);

Finish this article! I hope you have some help, O (∩_∩) o

HTTP client Transfer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.