System. Net. Http for Silverlight

Source: Internet
Author: User
Introduction to System. Net. Http

System. Net. Http is the latest HTTP application programming interface launched by Microsoft. Microsoft calls it a "modern HTTP programming interface" and aims to provide the following content:

  1. Users use modern Web Service client components through HTTP;
  2. HTTP components (such as processing HTTP headers and messages) that can be used by both the client and the server to provide consistent programming models for the client and the server.

The namespace System. Net. Http and System. Net. Http. Headers provide the following content:

  1. HttpClient sends and receives HTTP requests and responses;
  2. HttpRequestMessage and HttpResponseMessage encapsulate the HTTP message defined in RFC 2616;
  3. HttpHeaders encapsulates the HTTP header defined in RFC 2616;
  4. HttpClientHandler is responsible for generating the HTTP processing program for the HTTP Response Message.

System. Net. Http can process multiple types of HTTP Entity bodies defined in RFC 2616, as shown in:

In addition, System. Net. Http uses the responsibility chain mode to process HTTP messages. Here we have a good introduction and I will not talk about it more here.

System. Net. Http in Silverlight

System. Net. Http first appeared at the same time as Asp. Net Mvc4, which can be used in. Net 4.0. With. net 4.5 release, System. net. http officially became. net base class library. Currently.. Net 4.0/4.5, Windows Phone, and Windows Store App. net. http. Even more sadly, with the release of Xamarin 2.0, Xamarin. Android and Xamarin. iOS began to support System. Net. Http, which made the development of Silverlight cool.

Fortunately ,. net has an open-source implementation, that is, Mono, which has a large number of open-source. net basic class implementation. In Mono 3.x, there is an open-source System. net. android and iOS versions released by Http and Xamarin. net. http is originated from Mono. Since Android and iOS can, I believe Silverlight can also be used. I downloaded the System under Mono with a try attitude. net. the Http source code is compiled into a Silverlight project. After some effort, the Silverlight version of System. Net. Http can finally be used, GitHub Project address: https://github.com/beginor/System_Net_Http, welcome onlookers.

Due to HTTP restrictions on the Silverlight platform, some features such as Proxy, AllowAutoRedirect, PreAuthenticate, and KeepAlive settings are removed, which are not supported by Silverlight.

For BrowserHttp of Silverlight, only the GET and POST methods are supported. The sample code is as follows:

HttpClient client = new HttpClient {   BaseAddress = new Uri("http://localhost:8080/HttpTestWeb/api/")};// Get string from serverclient.GetStringAsync("browserhttp/").ContinueWith(t => {   if (t.IsFaulted) {      // report error here      //Application.Current.ReportError(t.Exception.GetBaseException());   } else {      string txt = t.Result;      //Assert.IsFalse(string.IsNullOrEmpty(txt));   }});// Post form data to servervar param = new Dictionary<string, string> {   {"Name", "Client Post"},   {"Age", "1"},   {"Birthday", DateTime.Today.ToString("s")}};client.PostAsync("browserhttp/", new FormUrlEncodedContent(param)).ContinueWith(t => {   if (t.IsFaulted) {      // report error here      // Application.Current.ReportError(t.Exception.GetBaseException());   } else {      HttpResponseMessage response = t.Result;      //Assert.IsTrue(response.EnsureSuccessStatusCode);   }});

In addition to GET and POST, ClientHttp also supports PUT and DELETE (Other HTTP methods may also support, not tested). The sample code is as follows:

// PUT to updatevar param = new Dictionary<string, string> {   {"Id", "1" },   {"Name", "Client Post"},   {"Age", "1"},   {"Birthday", DateTime.Today.ToString("s")}};client.PutAsync("clienthttp/1", new FormUrlEncodedContent(param)).ContinueWith(t => {   if (t.IsFaulted) {      // report error here      // Application.Current.ReportError(t.Exception.GetBaseException());   } else {      HttpResponseMessage response = t.Result;      //Assert.IsTrue(response.EnsureSuccessStatusCode);   }});// DELETEclient.DeleteAsync("clienthttp/1").ContinueWith(t => {   if (t.IsFaulted) {      // report error here      // Application.Current.ReportError(t.Exception.GetBaseException());   } else {      HttpResponseMessage response = t.Result;      //Assert.IsTrue(response.EnsureSuccessStatusCode);   }});

MessageProcessingHandler that supports the responsibility chain mode is shown in the following code:

public class CustomProcessingHandler : MessageProcessingHandler {   protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken) {      if (request.Method != HttpMethod.Get && request.Method != HttpMethod.Post) {         request.Headers.TryAddWithoutValidation("RequestMethod", request.Method.Method);         request.Method = HttpMethod.Post;      }      return request;   }   protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken) {      var request = response.RequestMessage;      if (request.Headers.Contains("RequestMethod")) {         IEnumerable<string> values;         if (request.Headers.TryGetValues("RequestMethod", out values)) {            request.Method = new HttpMethod(values.First());         }      }      return response;   }}

It is also very simple to use:

var customHandler = new CustomProcessingHandler {    InnerHandler = new HttpClientHandler()};var client = new HttpClient(customHandler, true) {    BaseAddress = new Uri("http://localhost:8080/HttpTestWeb/api/")};
References:
  • MSDN official documentation: http://msdn.microsoft.com/library/system.net.http.aspx
  • Working with HTTP: http://www.asp.net/web-api/overview/working-with-http in ASP. NET Web API Introduction
  • Mono source code: https://github.com/mono/mono/tree/master/mcs/class/System.Net.Http

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.