Introduction to System. Net. Http (1) -- Introduction to System. Net. Http (transfer) and introduction to systemtalks
I am going to learn about System. Net. Http. I want to refer to it and record it myself when I see a very detailed article. The original address is http://www.cnblogs.com/chillsrc/p/3439215.html? Utm_source = tuicool & utm_medium = referral
System. Net. Http is the latest HTTP application programming interface launched by Microsoft. It is called a "modern HTTP programming interface" and mainly provides 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 at the same time on 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 first appeared at the same time as Asp. Net Mvc4. It is a third-party component named Microsoft HTTP Client Libraries and can be used in. Net 4.0. With the release of. Net 4.5, System. Net. Http has officially become a. Net base class library and can be used in. Net 4.0/4.5, Windows Phone, and Windows Store apps.
The HttpClient component class instance sends an HTTP request to a session. When the HttpClient instance is set to a set, all requests executed by the instance are applied. In addition, each HttpClient instance uses its own connection pool to isolate the execution requests of other HttpClient instances. HttpClient is also a more specific base class of the HTTP client.
By default, HttpWebRequest is used to send requests to the server. This line can be changed by specifying different channels in the constructor overload that accepts an HttpMessageHandler instance as the parameter.
If identity authentication or caching is required, WebRequestHandler can use configuration items and instances to pass to the constructor. The returned handler is passed to a construction that uses the HttpMessageHandler parameter to pass the returned parameter.
If you use an app of HttpClient and related component classes in the System. net. the Http namespace is used to download a large amount of data (up to 50 MB or more), the application should download these streams and do not use the default buffer. If the default value is used, the memory usage of the buffer client is very large, which may cause significant performance degradation.
For the basic usage of HttpClient, the sample code is as follows:
// Declare HttpClient
HttpClient client = new HttpClient
{
BaseAddress = new Uri ("http://www.163.com ")
};
// Enable information display across threads in multiple threads
Public delegate void ShowMsgDelegate (string text );
Public void ShowMsgText (string text)
{
TxtMsg. Text = text;
}
// Display information
Private void ShowMessage (string msg)
{
If (this. InvokeRequired)
{
This. Invoke (new ShowMsgDelegate (ShowMsgText), msg );
}
Else
{
ShowMsgText (msg );
}
}
// Get form data to server
Private void btnGet_Click (object sender, EventArgs e)
{
// Get string from server
Client. GetStringAsync ("browserhttp/"). ContinueWith (t =>
{
If (t. IsFaulted)
{
ShowMessage ("returned information error:" + t. Result );
}
Else
{
ShowMessage ("success:" + t. Result );
}
});
}
// Post form data to server
Private void btnPost_Click (object sender, EventArgs e)
{
Var param = new Dictionary <string, string> {
{"Name", "TOM Post "},
{"Age", "11 "},
{"Birthday", DateTime. Now. ToString ("yyyyMMdd ")}
};
Client. PostAsync ("browserhttp/", new FormUrlEncodedContent (param). ContinueWith (t =>
{
ShowMsgDelegate showmsg = new ShowMsgDelegate (ShowMsgText );
If (t. IsFaulted)
{
ShowMessage ("returned information error:" + t. Result );
}
Else
{
HttpResponseMessage response = t. Result;
ShowMessage (response. StatusCode. ToString ());
}
});
}
// PUT to update
Private void btnPut_Click (object sender, EventArgs e)
{
Var param = new Dictionary <string, string> {
{"Id", "10 "},
{"Name", "Tom Post "},
{"Age", "10 "},
{"Birthday", DateTime. Now. ToString ("yyyyMMdd ")}
};
Client. PutAsync ("clienthttp/1", new FormUrlEncodedContent (param). ContinueWith (t =>
{
If (t. IsFaulted)
{
ShowMessage ("returned information error:" + t. Result );
}
Else
{
HttpResponseMessage response = t. Result;
ShowMessage (response. StatusCode. ToString ());
}
});
}
// DELETE
Private void btnDel_Click (object sender, EventArgs e)
{
Client. DeleteAsync ("clienthttp/1"). ContinueWith (t =>
{
If (t. IsFaulted)
{
ShowMessage ("returned information error:" + t. Result );
}
Else
{
HttpResponseMessage response = t. Result;
ShowMessage (response. StatusCode. ToString ());
}
});
}
MessageProcessingHandler and MessageProcessingHandler In the responsibility chain mode are supported-a basic HTTP message processing program. This is the easiest way to derive a processing program and should serve as the starting point for most custom processing programs. You have defined a new MessageProcessingHandler handler, as shown in the following sample 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:
Private void btnCustom_Click (object sender, EventArgs e)
{
Var customHandler = new CustomProcessingHandler
{
InnerHandler = new HttpClientHandler ()
};
Var client = new HttpClient (customHandler, true)
{
BaseAddress = new Uri ("http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl ")
};
Var task = client. GetAsync (client. BaseAddress );
Task. Result. EnsureSuccessStatusCode ();
HttpResponseMessage response = task. Result;
TxtStatusCode. Text = response. StatusCode + "" + response. ReasonPhrase + Environment. NewLine;
TxtStatusText. Text = "the returned results of the request are as follows ...";
Var result = response. Content. ReadAsStringAsync ();
TxtMsg. Text = result. Result ;;
}