[In Layman WP8.1 (RUNTIME)] Network programming HttpClient class

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:

    New Uri ("http://yourwebsite.com");     New HttpClient ();     // gets the returned string data    for the network string 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:

    await Httpclient.getasync (URI);     string 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 = (awaitResponse. Content.readasinputstreamasync ()). Asstreamforread ()) {intRead =0; byte[] ResponseBytes =New byte[ +];  Do        {            //if read equals 0 data for the stream and the read is completeRead=awaitResponsestream.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.

    PrivateCancellationTokenSource cts =NewCancellationTokenSource (); Try    {        //use the CancellationTokenSource object to control the cancel operation of an asynchronous taskhttpresponsemessage Response=awaitHttpclient.getasync (NewUri (resourceaddress)). AsTask (CTS.        Token); Responsebody=awaitResponse. Content.readasstringasync (). AsTask (CTS.        Token); Cts.    Token.throwifcancellationrequested (); }    Catch(taskcanceledexception) {responsebody="The request was canceled"; }    //Call the Cancel method to cancel a 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  New httpstringcontent ("Hello Windows Phone");     await Httpclient.postasync (URI,                                           httpstringcontent). AsTask (CTS. Token);     string await response. Content.readasstringasync (). AsTask (CTS. Token);

(2) Post request sends data stream data

    New Httpstreamcontent (stream. Asinputstream ());     await Httpclient.postasync (URI,                                           streamcontent). AsTask (CTS. Token);     string 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 objecthttpstreamcontent streamcontent=NewHttpstreamcontent (stream.    Asinputstream ()); Httprequestmessage Request=NewHttprequestmessage (Httpmethod.post,NewUri (resourceaddress)); Request. Content=streamcontent; //Send Datahttpresponsemessage Response=awaitHttpclient.sendrequestasync (Request). AsTask (CTS.    Token); stringResponsebody =awaitResponse. 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 New Httpbaseprotocolfilter ();           // get cookie information for addresses that have network requests using httpclient through the Httpbaseprotocolfilter object      = filter. Cookiemanager.getcookies (new  Uri (resourceaddress));     // Cookie Information    that traverses the entire cookie collection foreach inch 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 serverHttpCookie Cookies=NewHttpCookie ("ID","yourwebsite.com","/"); //set the value of a cookiecookies. Value="123456"; //sets the time at which the cookie will survive if set to NULL indicates that it is only valid in one sessioncookies. Expires=NewDateTimeOffset (DateTime.Now,NewTimeSpan (0,1,8)); //set cookies inside the filterhttpbaseprotocolfilter Filter=NewHttpbaseprotocolfilter (); BOOLreplaced = filter. Cookiemanager.setcookie (Cookies,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 a IprogressIProgress<HttpProgress> progress =NewProgress(Progresshandler); //adding progress monitoring to an asynchronous taskhttpresponsemessage Response=awaitHttpclient.postasync (NewUri (resourceaddress), streamcontent). AsTask (CTS.    Token, progress); //callback method for progress monitoring    Private voidProgresshandler (httpprogress progress) {//Here you can get information about progress through the progress parameter    }

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

Source code Download: Http://vdisk.weibo.com/s/zt_pyrfNHb99O

Welcome to follow my Weibo @wp forestry Administration public Number: WP Development (No.: WPKAIFA)

WP8.1 Technology Group: 372552293

[In Layman WP8.1 (RUNTIME)] Network programming HttpClient class

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.