[In layman's Windows 10] network programming HttpClient class

Source: Internet
Author: User
Tags try catch

14.2 HttpClient class of network programming

In addition to using the HttpWebRequest class to implement HTTP network requests, you 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.

14.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. Here's 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 you want to get the entire object returned by the HTTP request 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. The following uses 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 the stream and the read is 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 the CancellationTokenSource object to cancel an asynchronous request, the taskcanceledexception exception is triggered, and the exception needs to be captured with a try catch statement to recognize that the request was canceled.

Private CancellationTokenSource cts = new CancellationTokenSource ();

Try

{

Use the CancellationTokenSource object to control the cancel operation of an 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 a network request

if (CTS. token.canbecanceled)

{

Cts. Cancel ();

}

14.2.2 Post request to send string and data stream data

Using the HttpClient class to initiate a POST request is also very concise, and you can call the method Postasync (Uri Uri, ihttpcontent content) to post 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 first initializes the data into a Ihttpcontent object, implements the Ihttpcontent interface class has the Httpstringcontent class, The Httpstreamcontent class and the Httpbuffercontent class, these three class sub-tables represent string types, data flow types, and binary types, and 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 10");

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, you can use the Sendrequestasync method to send network requests, and the Sendrequestasync method can use either the Get mode or the post mode. 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);

14.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. When using HTTP requests, if the data returned by the server to be used for cookie data is available, it is stored locally, and the next time an HTTP request is made, the data for these cookies will be taken.

In the HttpClient class, the Httpbaseprotocolfilter class can be used to obtain the cookie information of the website. 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 ();

Get cookie information for addresses that have network requests using httpclient through the Httpbaseprotocolfilter object

HttpCookieCollection cookiecollection = filter. Cookiemanager.getcookies (New Uri (resourceaddress));

Cookie information that traverses the entire cookie collection

foreach (HttpCookie cookie in cookiecollection)

{

}

Of course, when sending an HTTP request, it is also possible to bring cookie information, if the server can recognize the cookie information through the cookie information to do something, such as cookie information with the user name and password encryption information, then you can eliminate the steps to sign in. 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 value of a cookie

Cookies. Value = "123456";

Sets the time at which the cookie will survive if set to NULL indicates that it is only valid in one session

Cookies. Expires = new DateTimeOffset (DateTime.Now, New TimeSpan (0, 1, 8));

Set cookies inside 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

14.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 Iprogress

iprogress

Adding progress monitoring to an asynchronous task

Httpresponsemessage response = await Httpclient.postasync (new Uri (resourceaddress), streamcontent). AsTask (CTS. Token, progress);

callback method for progress monitoring

private void Progresshandler (httpprogress progress)

{

Here you can get information about progress through the progress parameter

}

14.2.5 Custom HTTP request filters

An HTTP request filter is a powerful feature of HttpClient network requests, which can encapsulate each network request rule as a common filter to use, making WEB requests for specific connections and security scenarios easier. We can use logic such as authentication, data encryption, and automatic retry after the connection fails to encapsulate the filter, and then use a filter to initialize a HttpClient object for network requests.

Typically, it is easy to handle a network or security condition that may occur during a request, but it can be difficult to handle multiple networks or security conditions. You can create some simple filters and then link them as needed. This allows you to develop some WEB request functionality for the expected complications without the need to develop very complex programs.

HttpClient is the main class for sending and receiving requests over HTTP, and it uses the Httpbaseprotocolfilter class to determine how to send and receive data, so httpbaseprotocolfilter is logically the end of all custom filter chains. Each httpclient instance can have a different filter chain or pipeline, as shown in 14.3.

Figure 14.3 Filter chain model for httpclient requests

To write a custom filter, you need to create a custom filter class to implement the Ihttpfilter interface, The Ihttpfilter.sendrequestasync method is used to specify how the filter works, that is, the information that you encapsulate for the network request is placed inside the method, and the method is called internally by the filter when the network request is initiated. You can use C #, Visual Basic. NET, or C + + to write filters, and these filters can be invoked and used in all languages supported by the Windows runtime. Here's a sample code for a filter that adds a custom header to an HTTP request and response.

Create a custom filter use this filter to add a custom HTTP header message in both the HTTP request and the corresponding

public class Pluginfilter:ihttpfilter

{

Private Ihttpfilter Innerfilter;

Public Pluginfilter (Ihttpfilter innerfilter)

{

if (Innerfilter = = null)

{

throw new ArgumentException ("Innerfilter cannot be null.");

}

This.innerfilter = Innerfilter;

}

Add a custom HTTP header to the Sendrequestasync method

Public Iasyncoperationwithprogress

{

Return asyncinfo.run

{

Add a request Header

Request. Headers.add ("Custom-header", "Customrequestvalue");

Httpresponsemessage response = await innerfilter.sendrequestasync (request). AsTask (CancellationToken, progress);

Cancellationtoken.throwifcancellationrequested ();

Add the appropriate header

Response. Headers.add ("Custom-header", "Customresponsevalue");

return response;

});

}

public void Dispose ()

{

Innerfilter.dispose ();

Gc. SuppressFinalize (this);

}

}

To use this filter, pass its interface to the HttpClient (ihttpfilter) Construction method when the HttpClient object is created. To set the filter chain, link the new filter to the previous filter and the Httpbaseprotocolfilter object at the end of the chain. The following uses the Pluginfilter filter to create the HttpClient object, as shown in the following code:

Create a Httpbaseprotocolfilter object first, because this is the bottom-most filter of the httpclient default

var basefilter = new Httpbaseprotocolfilter ();

Create a Pluginfilter filter object that is linked to the Httpbaseprotocolfilter object

var myfilter = new Pluginfilter (basefilter);

Create a HttpClient object using a custom filter

HttpClient HttpClient = new HttpClient (myfilter);

...... The following use of the HttpClient object to initiate a network request will automatically bring the HTTP headers added by the custom filter

This article is from the general application development of Windows 10 in layman's

Source code Download: http://vdisk.weibo.com/u/2186322691

Catalog: http://www.cnblogs.com/linzheng/p/5021428.html

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

WINDOWS10/WP Technology Group: 284783431

[In layman's Windows 10] 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.