Two HttpClient APIs in UWP (General Windows Platform), uwphttpclient

Source: Internet
Author: User
Tags microsoft edge

Two HttpClient APIs in UWP (General Windows Platform), uwphttpclient

UWP (Universal Windows platform) application developers can choose from multiple APIs when building an application that interacts with Web services or server breakpoints through HTTP. To implement the HTTP client role in a hosted UWP application, the two most common APIs are System. Net. Http. HttpClient and Windows. Web. Http. HttpClient. RelativeWebClientAndHttpWebRequestFor old and outdated APIs, the above two APIs should be preferred (despite backward compatibility considerations,HttpWebRequest).

Many developers have questions about the similarities and differences between the two APIs and how to choose them. This article aims to answer these questions and clarify the respective uses of the two APIs.

Overview

System.Net.Http.HttpClientThis API was introduced for the first time in. NET 4.5, and there is also a variant that supports the. NET 4.0 and Windows Phone 8 Silverlight applications in the form of NuGet packages. The purpose of this API is to provide an olderHttpWebRequestThe abstract layer of APIS is simpler and clearer, and the implementation of HTTP client roles is more flexible and flexible. For example, developers can intercept each request or response and implement custom logic through the chained Custom handler provided by them. Until the Windows 8.1 location, the underlying layer of the API is implemented by pure. NET. In Windows 10, the UWP implementation of this API has been changedWindows.Web.HttpAnd WinINet HTTP protocol stack.

On the other hand,Windows.Web.Http.HttpClientAPIs are introduced in Windows 8.1 and can be used in Windows Phone 8.1. The biggest motivation for creating this API is to integrate the HTTP APIs available in various Windows application development languages so that an API can provide all the features of their respective APIs. Most of the basic APIs are designed fromSystem.Net.HttpThe implementation is based on the WinINet HTTP protocol stack.

When using the two APIs in Windows Store applications, the operating system version and programming language are supported as follows:

API Operating system version Supported languages
System. Net. Http. HttpClient Windows, Windows Phone 8 or above . NET language only
Windows. Web. Http. HttpClient Windows, Windows Phone 8.1 or above All Windows Store application languages
How to choose?

Both APIs are available in UWP, so the biggest problem for HTTP developers is which one of them should be selected in the application. The selection result depends on some specific factors.

Object Model

Now we have understood the reasons for creating these two similar APIs and how to choose the Basic Principles. Next we will take a closer look at their respective object models.

System. Net. Http

The top-level abstraction layer of the API object model is the HttpClient object.HttpClientThe object indicates the client entity in the client-server model depicted by HTTP. The client can send multiple requests (represented by HttpRequestMessage) to the server and receive corresponding responses (represented by HttpResponseMessage ). The entity body and content header of each HTTP request or response are composed of the base class HttpContent and its derived class.StreamContent,MultipartContentAndStringContent. These types represent different types of HTTP entity bodies. These types provide a setReadAs*The method reads the entity body of a request or response as a string, a coarse number of bytes, or a stream.

EachHttpClientThere is a handler object at the bottom of the object to indicate all client HTTP settings. You can conceptually regard handler as the underlying HTTP stack of the client. It is responsible for sending the HTTP request from the client to the server and returning the corresponding response.

System.Net.HttpThe default handler class in the API is HttpClientHandler. When you createHttpClientWhen a new instance of an object is called, for examplenew HttpClient()-- OneHttpClientHandlerThe object is automatically created and carries the default HTTP stack settings. If you want to modify the cache behavior, automatic compression, creden, or proxy settings, you can createHttpClientHandlerInstance, modify the corresponding properties, and pass themHttpClientConstructor:

1 HttpClientHandler myHandler = new HttpClientHandler();  2 myHandler.AllowAutoRedirect = false;  3 HttpClient myClient = new HttpClient(myHandler);  
Chain Handler

System.Net.Http.HttpClientOne of the key advantages in API design is thatHttpClientInsert a Custom handler into the bottom layer of the object and create a handler object chain. Suppose you want to build an application that needs to query data from Web Services. You have compiled a custom logic to handle HTTP 4xx (client error) and 5xx (server error) errors returned from the server, and initiated retry actions such as replacing the endpoint or adding user creden. You also want to separate the HTTP-related work from other business logic that processes the data returned by Web Services.

To meet the preceding requirements, you can derive a new handler class from DelegatingHandler (for example, CustomHandler1), create an instance of the derived class, and pass itHttpClientConstructor.DelegatingHandlerClassInnerHandlerAttribute is used to specify the next handler in the chain -- for example, you can add another Custom handler (such as CustomHandler2) to the chain. In the last handler, you canInnerHandlerSet toHttpClientHandlerInstance, the instance will pass the request to the system's HTTP stack. The process is shown in:

Sample Code to complete the preceding requirements:

1 public class CustomHandler1: DelegatingHandler 2 {3 // place the constructor and other code here. 4 protected async override Task <HttpResponseMessage> SendAsync (5 HttpRequestMessage request, CancellationToken cancellationToken) 6 {7 // process the HttpRequestMessage object here. 8. Debug. writeLine ("Processing request in Custom Handler 1"); 9 10 // call DelegatingHandler once the previous step is complete. sendAsync continues to pass it to inner handler11 HttpResponseMessage response = await base. sendAsync (request, cancellationToken); 12 13 // process the returned HttpResponseMessage object here. 14 Debug. writeLine ("Processing response in Custom Handler 1"); 15 16 return response; 17} 18} 19 20 public class CustomHandler2: delegatingHandler 21 {22 // content is similar to CustomHandler1 23} 24 public class Foo 25 {26 public void CreateHttpClientWithChain () 27 {28 HttpClientHandler systemHandler = new HttpClientHandler (); 29 CustomHandler1 myHandler1 = new CustomHandler1 (); 30 CustomHandler2 myHandler2 = new Cu StomHandler2 (); 31 32 // link two Handler together. 33 myHandler1.InnerHandler = myHandler2; 34 myHandler2.InnerHandler = systemHandler; 35 36 // use the top-level Handler in the chain to create client objects. 37 HttpClient myClient = new HttpClient (myHandler1); 38} 39}

Note:

For more information about chained Handler, refer to the article written by Henrik Nielsen (note that the API mentioned in this Article refers to ASP. NET Web API version, which is discussed in this article. NET Framework is slightly different, but the concept of chained handler is common .)

Windows. Web. Http

Windows.Web.HttpThe Object Mode of the API andSystem.Net.HttpSimilarly, it also includes the client entity, handler (called "filter" in the namespace), and inserting custom logic between the client and the system's default filter.

Most types of this API andSystem.Net.HttpThe object model of is similar:

HTTP client role Representation System. Net. Http type Corresponding to the Windows. Web. Http type
Client entity HttpClient HttpClient
HTTP Request HttpRequestMessage HttpRequestMessage
HTTP Response HttpResponseMessage HttpResponseMessage
Entity body of HTTP or response HttpContent IHttpContent
HTTP Content string, stream, and other representation StringContent, StreamContent and ByteArrayContent HttpStringContent, HttpStreamContent and HttpBufferContent respectively
HTTP stack/settings HttpClientHandler HttpBaseProtocolFilter
Base Class/interface used to create custom handlers/filters DelegatingHandler IHttpFilter

AboutSystem.Net.HttpThe discussion of API chain handler can also be usedWindows.Web.HttpAPI. You can create a set of chained custom filters that are passed to the constructor of the HttpClient object.

Common HTTP scenarios

Now let's take a look at some code snippets and use two HttpClient APIs to implement common HTTP scenarios. For more details and guidance, see the MSDN documentation for Windows. Web. Http. HttpClient and System. Net. Http. HttpClient.

Modify Header

System. Net. Http:

Modify the headers of all requests sent by the HttpClient instance:

1 var myClient = new HttpClient();  2 myClient.DefaultRequestHeaders.Add("X-HeaderKey", "HeaderValue");  3 myClient.DefaultRequestHeaders.Referrer = new Uri("http://www.contoso.com");  

Modify only the headers of a specific request:

1 HttpRequestMessage myrequest = new HttpRequestMessage();  2 myrequest.Headers.Add("X-HeaderKey", "HeaderValue");  3 myrequest.Headers.Referrer = new Uri("http://www.contoso.com");  

Windows. Web. Http:

The above Code also appliesWindows.Web.HttpAPI.

Note:

Timeout settings

System. Net. Http:

InSystem.Net.HttpAPI, there are two ways to set timeout. To set timeout for all requests sent from the client, use:

1 myClient.Timeout = TimeSpan.FromSeconds(30); 

To set timeout for a single request, use CancellationToken:

1 var cts = new CancellationTokenSource (); 2 cts. cancelAfter (TimeSpan. fromSeconds (30); 3 4 var httpClient = new HttpClient (); 5 var resourceUri = new Uri ("http://www.contoso.com"); 6 7 try 8 {9 HttpResponseMessage response = await httpClient. getAsync (resourceUri, cts. token); 10} 11 catch (TaskCanceledException ex) 12 {13 // logic of canceling the request due to timeout 14} 15 catch (HttpRequestException ex) 16 {17 // logic for handling other possible exceptions 18}

Windows. Web. Http:

Windows.Web.Http.HttpClientNo timeout attribute is available in the type, so you must use CancellationToken as mentioned above to implement timeout processing.

Use authentication creden

System. Net. Http:

To protect your creden, the HTTP stack does not add any authentication creden。 to requests by default. To use the creden of the specified user, use the following method:

1 var myClientHandler = new HttpClientHandler();  2 myClientHandler.Credentials = new NetworkCredential(myUsername, myPassword);  

Windows. Web. Http:

ForWindows.Web.HttpAPI. By default, if a request is sent to access a resource that requires user authentication, a UI dialog box is displayed. To close the UI dialog box, you canHttpBaseProtocolFilterOfAllowUISet property to false. To use the creden of the specified user, use the following method:

1 var myFilter = new HttpBaseProtocolFilter();  2 myFilter.ServerCredential = new PasswordCredential(“fooBar”, myUsername, myPassword);  

Note:

Use client certificate

System. Net. Http:

To protect user creden, this API does not send any client certificate to the server by default. To use a client certificate for verification, use the following method:

1 var myClientHandler = new HttpClientHandler();  2 myClientHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;  

Windows. Web. Http:

There are two options to use this API for client certificate verification-the default method is to bring up a UI for the user to select a certificate; the other option is to specify a client certificate in the Code:

1 var myFilter = new HttpBaseProtocolFilter();  2 myFilter.ClientCertificate = myCertificate;  

Note:

Proxy Settings

By default, proxy settings for both APIs are automatically configured for all HTTP calls based on Internet Explorer/Microsoft Edge settings. This allows the application to work normally when the user connects to the network through a proxy. Neither API provides any method to specify a custom proxy for the application. However, you can setHttpClientHandler.UseProxySet to false or in Windows. Web. HttpHttpBaseProtocolFilter.UseProxyIf this parameter is set to false, the default proxy configuration is disabled.

Cookie Processing

By default, both APIs Save the cookie data sent by the server and automatically append the data to the subsequent requests for the same application container URI. The cookie of a specific URI can also read or add custom cookie data. Finally, both APIs provide options to disable cookie sending to the server:System.Net.Http, Set HttpClientHandler. UseCookies to false.Windows.Web.HttpSet HttpBaseProtocolFilter. CookieUsageBehavior to HttpCookieUsageBehavior. NoCookies.

System. Net. Http:

Add a cookie for all requests generated by the client:

1 // manually add a cookie. 2 myClientHandler. CookieContainer. Add (resourceUri, myCookie );

Add a cookie for a single request:

1 HttpRequestMessage myRequest = new HttpRequestMessage();  2 myRequest.Headers.Add("Cookie", "user=foo; key=bar");  

View All cookies of a given URI:

1 var cookieCollection = myClientHandler.CookieContainer.GetCookies(resourceUri);  

Windows. Web. Http:

Add a cookie for all requests generated by the client:

1 // manually add a cookie. 2 filter. CookieManager. SetCookie (myCookie );

The preceding example adds a cookie for a single request.Windows.Web.HttpAPI.

Manage cookies:

1 // obtain all cookies for a given URI. 2 var cookieCollection = filter. CookieManager. GetCookies (resourceUri); 3 4 // delete a cookie. 5 filter. CookieManager. DeleteCookie (myCookie );

Note:

Maximum number of connections per server

By default, the underlying HTTP stack of the operating system can use up to six connections for each server.System.Net.HttpThe HttpClient API does not provide any method to control the maximum number of connections. ForWindows.Web.HttpAPI, you can set it using the following method:

1 var myFilter = new HttpBaseProtocolFilter();  2 myFilter.MaxConnectionsPerServer = 15;  
Others

In Windows 10, UWP supports HTTP/2 in both APIs. This feature is enabled by default, so developers can enjoy lower latency without any code modifications. Two APIs (System.Net.HttpAndWindows.Web.HttpYou can also manually disable this feature and force the HTTP Version to 1.1 or 1.0.

 

This article is compiled from the Microsoft Building Apps for Windows blog. the original address is Demystifying HttpClient APIs in the Universal Windows Platform. This article was originally written by Program Manager Sidharth Nabar of the Windows Network API group.

Abstract: This article is a personal blog backup article, the original address: http://validvoid.net/demystifying-httpclient-apis-in-the-uwp/

Related Article

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.