Not "simple" HttpClient

Source: Internet
Author: User

HTTP is the most important contributor to the success of the Web. The most important reason for the success of HTTP is its simplicity.

In. NET Framework 4.5, Microsoft brought System. Net. Http. HttpClient to everyone. Now it is called HttpClient. I think it should be simpler than HttpWebRequest to cater to the simple features of HTTP.

In the previous blog POST "jQuery can do it, PHP can do it, and C # can do it", we also found that using HttpClient to initiate an http post request and pass the url query string parameter, which is easier than using HttpWebRequest. So I plan to change the implementation based on HttpWebRequest to the implementation based on HttpClient.

The following code sets the UserAgent in the HttpWebRequest-based implementation:

var webRequest = WebRequest.Create(url) as HttpWebRequest;webRequest.UserAgent = "CNBlogs";

I thought HttpClient had the same UserAgent attribute, so I wanted to write it like this:

Var httpClient = new HttpClient (); httpClient. UserAgent = "CNBlogs"; // error code

The result shows that HttpClient does not have the UserAgent attribute at all.

So I finally found a UserAgent:

var httpClient = new HttpClient();httpClient.DefaultRequestHeaders.UserAgent

The UserAgent is read-only.

The type of the constructor is HttpHeaderValueCollection <ProductInfoHeaderValue>. You can Add it. The parameter type of Add is ProductInfoHeaderValue, so it is new ProductInfoHeaderValue. The parameter type of the constructor is ProductHeaderValue. The Code is as follows:

var httpClient = new HttpClient();httpClient.DefaultRequestHeaders.UserAgent.Add(    new ProductInfoHeaderValue(        new ProductHeaderValue("CNBlogs")));

Run the code and check that the desired UserAgent is obtained. But it's complicated.

After touching the root vine, I found a slightly simpler melon, which can also be:

var httpClient = new HttpClient();httpClient.DefaultRequestHeaders.UserAgent.Add(    new ProductInfoHeaderValue("CNBlogs", null));

Set the email address in UserAgent as needed, so the code is changed:

var httpClient = new HttpClient();httpClient.DefaultRequestHeaders.UserAgent.Add(    new ProductInfoHeaderValue(        new ProductHeaderValue("contact@cnblogs.com")));

An error occurred while running the result:

Failed: System. FormatException: The format of value 'Contact @ cnblogs.com 'is invalid.
At System. Net. Http. Headers. HeaderUtilities. CheckValidToken (String value, String parameterName)
At System. Net. Http. Headers. ProductHeaderValue.. ctor (String name)

In HttpWebRequest, it is possible:

var webRequest = WebRequest.Create(url) as HttpWebRequest;webRequest.UserAgent = "contact@cnblogs.com";

After touching for a long time, I found a half-baked melon...

Forget it. Let's take a look at Google... Find a line of code in How to use HttpClient handlers:

httpClient.DefaultRequestHeaders.Add("user-agent", "...");

Once the experts take a shot, they will know if there is any. You can simply change it to this Code:

var httpClient = new HttpClient();httpClient.DefaultRequestHeaders.Add("UserAgent", "contact@cnblogs.com");

This should be the easiest way to set UserAgent in HtppClient. The corresponding implementation of HttpWebRequest is:

var webRequest = WebRequest.Create(url) as HttpWebRequest;webRequest.Headers.Add("UserAgent", "contact@cnblogs.com");

The solution is done. I thought HttpClient would be easier than HttpWebRequest. However, for a simple operation like setting UserAgent, you only need to enter ". "u", smart sensing can be found; using HttpClient is somewhat troublesome, not only does not have smart awareness, but also requires manual input of the string "UserAgent ".

I think most people first think of HttpClient. UserAgent when using HttpClient to set up UserAgent. A good design should be where the user thinks about it and where it appears. HttpClient, which is not "simple", needs to be hidden from users.

What is the difference between HttpClient and HttpWebRequest? Why does it seem different from HttpWebRequest?

On MSDN, this is the case:

By default, HttpWebRequest will be used to send requests to the server.

If an app using HttpClient and related classes in the System. Net. Http namespace intends to download large amounts of data (50 megabytes or more ).

HttpClient differs from HttpWebRequest because of the large amount of data in response to the request.

Later, I found this sentence in the Henrik's Blog:

The default HttpClient is the simplest way in which you can start sending requests. A single HttpClient can be used to send as your HTTP requests as you want concurrently so in your scenarios you can just create one HttpClient and then use that for all your requests.

The original answer is here! The most distinctive feature of HttpClient is that the same HttpClient instance can send multiple requests, and each request can be a completely different URL. An HttpWebRequest instance corresponds to a request of a Url. This is the biggest difference between HttpClient and HttpWebRequest.

I wrote this blog to criticize HttpClient. During the writing, I found that I was not familiar with HttpClient. However, the design of HttpClient is not simple enough.

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.