HttpClient Class of Network programming (RPM)

Source: Internet
Author: User
Tags try catch

12.2 HttpClient Class of network programming

In addition to using the HttpWebRequest class to implement HTTP network requests, we can also use the HttpClient class to implement. For basic request operations, the HttpClient class provides a simple interface to handle the most common tasks and provides reasonable default settings for authentication for most scenarios. For more complex HTTP operations, more features include methods for performing common operations (DELETE, GET, PUT, and POST), the ability to get, set, and delete cookies, support for common authentication settings and patterns, and HTTP request progress information provided on Async methods , access to Secure Sockets Layer (SSL) details about transport, features such as custom filters in advanced apps, and more.

12.2.1 GET request for string and data flow data

(1 ) Gets the string data

The HttpClient class uses the task-based Asynchronous pattern to provide a very simplified request operation, and you can directly call the HttpClient class Getstringasync method to get the string data returned to the network. Let's take a look at the use of GET requests to get the string returned by the network, the implementation of the code is very concise and simple, the sample code is as follows:

    Uri uri = new Uri ("http://yourwebsite.com");    HttpClient HttpClient = new HttpClient ();    Gets the returned string data for the network string    result = await httpclient.getstringasync (URI);

Using the Getstringasync method is a simplified HTTP request, and the Getasync method can be used if we want to get the entire object returned by the HTTP request to the Httpresponsemessage class object. The Httpresponsemessage object is the appropriate message object for HTTP, which contains information such as the appropriate HTTP header, data body, and so on for the network request. Here we use the Getasync method to get the string information returned by the network, as shown in the sample code:

    Httpresponsemessage response = await httpclient.getasync (URI);    String responsebody = await response. Content.readasstringasync ();

(2 ) Get Data flow data

The content property of the Httpresponsemessage object represents the returned data object, which is an object of type Ihttpcontent. If you want to get data flow data, you can get to the returned Ibuffer object through its Readasbufferasync method, or get the Iinputstream object through Readasinputstreamasync place. And then into the stream object, the sample code looks like this:

    using (Stream Responsestream = (await response. Content.readasinputstreamasync ()). Asstreamforread ())    {        int read = 0;        byte[] responsebytes = new byte[1000];        Do        {            //If read equals 0 data for stream and reads complete read            = await Responsestream.readasync (responsebytes, 0, responsebytes.length);        } while (read! = 0);    }

(3 ) Cancel the network request

The HttpClient class initiates a network request that is a task-based asynchronous method, so canceling its asynchronous operation can be canceled by canceling the object CancellationTokenSource object of the asynchronous task, which is different from the HttpWebRequest class. If you use a CancellationTokenSource object to cancel an asynchronous request that triggers a taskcanceledexception exception, this exception requires that we capture it with a try catch statement to recognize that the request was canceled.

    Private CancellationTokenSource cts = new CancellationTokenSource ();    Try    {        //Use CancellationTokenSource object to control cancel operation of asynchronous task        httpresponsemessage response = await Httpclient.getasync (New Uri (resourceaddress)). AsTask (CTS. Token);        Responsebody = await response. Content.readasstringasync (). AsTask (CTS. Token);        Cts. Token.throwifcancellationrequested ();    }    catch (taskcanceledexception)    {        responsebody = "Request Canceled";    }    Call the Cancel method to cancel the network request    if (CTS. token.canbecanceled)    {        cts. Cancel ();    }

12.2.2 Post request to send string and data stream data

The programming of the POST request using the HttpClient class is also concise, and we can call the method Postasync (Uri Uri, ihttpcontent content) to post the data directly to the destination address, There are two parameters in the method where the URI is the destination address of the network, and a content of two is the data object that you want to post to the destination address. Before the post data we first initialize our data into a Ihttpcontent object, then the class that implements the Ihttpcontent interface has httpstringcontent class, The Httpstreamcontent class and the Httpbuffercontent class, these three class sub-tables represent string types, data flow types, and binary types, so the data flow type and binary type can be converted to each other with little difference. A Httpresponsemessage object is returned after the Postasync method is called, and we can get the result information returned after the POST request through the corresponding Message object of this HTTP. A code example for a POST request to send a string and data flow data is as follows:

(1) Post request to send string data

    Httpstringcontent  httpstringcontent = new Httpstringcontent ("Hello Windows Phone");    Httpresponsemessage response = await Httpclient.postasync (URI,                                           httpstringcontent). AsTask (CTS. Token);    String responsebody = await response. Content.readasstringasync (). AsTask (CTS. Token);

(2) Post request sends data stream data

    Httpstreamcontent streamcontent = new Httpstreamcontent (stream. Asinputstream ());    Httpresponsemessage response = await Httpclient.postasync (URI,                                           streamcontent). AsTask (CTS. Token);    String responsebody = await response. Content.readasstringasync (). AsTask (CTS. Token);

In addition to using the Postasync method, we can also use the Sendrequestasync method to send network requests, and the Sendrequestasync method can use either get or post. The message type that the Sendrequestasync method sends is the Httprequestmessage class object, and the Httprequestmessage class represents the request message class for HTTP. You can set the requested type (Get/post) and the transferred data object through the Httprequestmessage object. Examples of code that use the Sendrequestasync method are as follows:

    Create a Httprequestmessage object    httpstreamcontent streamcontent = new Httpstreamcontent (stream. Asinputstream ());    Httprequestmessage request = new Httprequestmessage (httpmethod.post, New Uri (resourceaddress));    Request. Content = streamcontent;    Send data    httpresponsemessage response = await httpclient.sendrequestasync (request). AsTask (CTS. Token);    String responsebody = await response. Content.readasstringasync (). AsTask (CTS. Token);

12.2.3 setting up and getting cookies

Cookies are data (usually encrypted) stored on the user's local terminal by certain websites in order to identify users and to track them back. So when we use HTTP requests, if the data returned by the server is to be used for cookie data, we can also get it, store it locally, and bring the cookie data the next time the HTTP request is launched.

In the HttpClient class network request, we can obtain the cookie information of the website through the Httpbaseprotocolfilter class. The Httpbaseprotocolfilter class represents a filter that is the underlying protocol of the HTTP request for HttpClient. An example of the code that gets the cookie is shown below:

    Create a Httpbaseprotocolfilter object    httpbaseprotocolfilter filter = new Httpbaseprotocolfilter ();    Use the Httpbaseprotocolfilter object to obtain cookie information for the address of the network request using HttpClient    httpcookiecollection cookiecollection = filter. Cookiemanager.getcookies (New Uri (resourceaddress));    Cookie information to traverse the entire cookie collection    foreach (HttpCookie cookie in cookiecollection)    {    }

Of course, when we send an HTTP request, we can also bring cookie information, if the server can recognize the cookie information, then through the cookie information to do some operations, such as cookie information with the user name and password encryption information, then you can eliminate the steps to login. In HttpClient's network request, the HttpCookie class represents a cookie object, and after creating the cookie object, the cookie is set by the Cookiemanager property of the Httpbaseprotocolfilter object. The network request then sends the cookie information to the network request. An example of the code that sets the cookie is shown below:

    Create a HttpCookie object, "id" means the name of the cookie, "localhost" is the hostname, "/" is the virtual path of the server    HttpCookie cookie = new HttpCookie ("id", " Yourwebsite.com ","/");    Set the cookie value    cookie. Value = "123456";    Sets the time that the cookie survives, and if set to NULL means that only the cookie is in effect within a session    . Expires = new DateTimeOffset (DateTime.Now, New TimeSpan (0, 1, 8));    Set a cookie in the filter    httpbaseprotocolfilter filter = new Httpbaseprotocolfilter ();    bool replaced = filter. Cookiemanager.setcookie (cookie, false);

...... Next, you can initiate a request to the "yourwebsite.com" remote host

12.2.4 Progress monitoring of network requests

HttpClient's network request is to support progress monitoring, the Iprogress<t> object of the asynchronous task can directly monitor the progress information returned by the HttpClient network request, and the progress object returned is the Httpprogress class object. The following information is included in the Progress Object httpprogress: Stage (current state), bytessent (size of data sent), bytesreceived (Received data size), retries (number of retries), Totalbytestosend (The total amount of data to be sent) and totalbytestoreceive (total data size to be received). A code example of network request progress monitoring is shown below:

    Create iprogress

This article is from the "in-depth Windows Phone 8.1 application Development"

WP8.1 Runtime article list: http://www.cnblogs.com/linzheng/p/3998037.html

HttpClient Class of Network programming (RPM)

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.