Introduction to ASP. net mvc Web API HttpClient

Source: Internet
Author: User
Tags microsoft website

1. Brief Introduction to HttpClient
I vaguely remember that at that time, I used WebClient and HttpWebRequest to send a request. Now ASP. NET MVC4 comes with a class HttpClient, which is used to receive HttpResponseMessage and send HttpRequestMesssage.
The problem is that since WebClient and HttpWebRequest can complete the corresponding functions, why should we use the HttpClient class ,. since such a class is proposed in the NET Framework, it must have its own special characteristics. Here are several differences:
(1) You can configure the extension on the HttpClient instance, set the default header, and cancel unfinished requests and settings.
(2) HttpClient has its own connection pool
(3) HttpClient is not bound to a specific server and can access any Http request.
(4) HttpClient uses asynchronous request processing

2. HttpClient remarks
HttpClient is included in the System.net. Http. dll program. The user accepts and sends http requests. This class applies to. NET4.0 or later versions.
By default, HttpWebRequest is used to send requests to the server. This action can specify a different channel to be modified as a parameter in one of the constructors that obtain the HttpMessageHandler instance. WebRequestHandler can be used to configure and set the functions or cache for authentication, and the instance can be passed to the constructor. The returned handler is passed to one of the constructors that use the HttpMessageHandler parameter.
For more information, refer to the official Microsoft Website:
Http://msdn.microsoft.com/zh-cn/library/system.net.http.httpclient.aspx

3. HttpClient basic operations
Copy codeThe Code is as follows:
Static void BasicMethod ()
{
String url = "http://www.baidu.com ";
HttpClient client = new HttpClient ();
String content = client. GetStringAsync (url). Result;
Console. WriteLine (content );
}

The above uses HttpClient to request the Baidu homepage. It seems that the operation is quite convenient. The result of running the output request is as follows:
 
The content output by the console is the request URL.
In addition to the GetStringAsync () method mentioned above, HttpClient also provides the following Get methods. For details, refer to MSDN:


4. custom request headers
To customize the request header, We need to inherit a class: HttpClientHandler
Public class GitHttpClientHandler: HttpClientHandler
Copy codeThe Code is as follows:
{
Protected override Task <HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken)
{
Request. Headers. Referrer = new Uri ("http://www.google.com /");
Request. Headers. Add ("UserAgent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2;. net clr 2.0.50727 )");

Task <HttpResponseMessage> task = base. SendAsync (request, cancellationToken );
HttpResponseMessage response = task. Result;
MediaTypeHeaderValue contentType = response. Content. Headers. ContentType;
If (string. IsNullOrEmpty (contentType. CharSet ))
{
ContentType. CharSet = "GBK ";
}
Return task;
}
}

HttpClientHandler is a common proxy mode. getStringAsync () adds an encapsulation layer to intercept the input and output of HttpClient to implement some custom operations. This method is very common in MVC and is the filter in MVC.
5. The request content is too long.
HttpClient has a MaxResponseContentBufferSize attribute, which indicates that the maximum number of bytes of cache is read. The default value is 64 K. When there are many page content, an exception is thrown if the number exceeds 64 K, result In Get failure.
We can manually set the size of this attribute:
Copy codeThe Code is as follows:
HttpClient client = new HttpClient () {MaxResponseContentBufferSize = 1024*1024 };

You can use the preceding method.
6. Chinese problems
Chinese problems are always a headache, and garbled characters often occur. The custom request header mentioned above can also be processed. Here we post a piece of code for reference. The Chinese problem is a bit complicated and needs to be handled according to the specific situation:
Copy codeThe Code is as follows:
HttpResponseMessage response = task. Result;
MediaTypeHeaderValue contentType = response. Content. Headers. ContentType;
If (string. IsNullOrEmpty (contentType. CharSet ))
{
ContentType. CharSet = "GBK ";
}

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.