How to select webclient, httpclient, Httpwebrequest in. Net

Time:2021-7-27

When we call restapi with. Net, we usually have three options:WebClient, HttpWebRequest,HttpClientIn this article, we will discuss how to use these three methods to call the restapi. I will also provide corresponding code cases to help you better understand the concepts and usage of these three methods. In short:

  • HttpWebRequestIt is a relatively low-level way to process HTTP request / response.

  • WebClientIt provides a high-level encapsulation of Httpwebrequest to simplify the invocation of users.

  • HttpClientIs a new toolkit for handling HTTP request / response, with higher performance.

Next, let’s talk about abstract classesWebRequest

WebRequest

Webrequest is an abstract class based on a specific HTTP implementation. Therefore, when processing reqeust requests, the bottom layer will generate corresponding subclasses according to the passed in URL, such as Httpwebrequest or filewebrequest. The following code shows how to use webrequest.

WebRequest webRequest = WebRequest.Create(uri);
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.Method ="GET";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

Webrequest is the first class used to process HTTP requests in the. Net frameworkHTTP requests and responsesAspect provides a lot of flexibility for callers. You can also use this class to access headers, cookies, protocols, timeouts, etc. the following code shows how its implementation subclass Httpwebrequest is used.

HttpWebRequest http = HttpWebRequest)WebRequest.Create(“http://localhost:8900/api/default”);
WebResponse response = http.GetResponse();
MemoryStream memoryStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(memoryStream);
string data = streamReader.ReadToEnd();

WebClient

Webclient is a high-level package of Httpwebrequest. It provides a more convenient way for callers to use it. Of course, the sacrifice is that the performance of webclient is slightly inferior to that of Httpwebrequest. If your business scenario is simply to access the HTTP service of a third party, I suggest you use webclient, Similarly, if you have more refined configurations, use Httpwebrequest. The following code shows how to use webclient.

string data = null;

using (var webClient = new WebClient())
{
    data = webClient.DownloadString(url);
}

HttpClient

Httpclient was introduced in. Net framework 4.5. If your project is based on. Net 4.5 or above, except for some specific reasons, it is recommended that you give priority to using httpclient. In essence, httpclient, as a later thing, absorbs the flexibility of Httpwebrequest and the convenience of webclient, so it can have both.

Httpwebrequest inrequest/responseObject provides very fine configuration. At the same time, you should also note that httpclient does not appear to replace webclient. The implication is that httpclient also has disadvantages, for example, it cannot be providedProgress processingandUri customization, FTP is not supported. Httpclient also has many advantages. All its IO operation methods are asynchronous. Of course, synchronous mode can also be used for special reasons. The following code shows how to use httpclient.

public async Task GetAuthorsAsync(string uri)
{
    Author author = null;
    HttpResponseMessage response = await client.GetAsync(uri);
    if (response.IsSuccessStatusCode)
    {
        author = await response.Content.ReadAsAsync();
    }
    return author;
}

It is worth noting that when the response error occurs, httpclient will not throw an exception by default. If you must ask httpclient to throw an exception in this case, you can change itIsSuccessStatusCode = falseTo change this default behavior, callresponse.EnsureSuccessStatusCode();

public async Task GetAuthorsAsync(string uri)
{
    Author author = null;

    HttpResponseMessage response = await client.GetAsync(uri);

    response.EnsureSuccessStatusCode();
    
    if (response.IsSuccessStatusCode)
    {
        author = await response.Content.ReadAsAsync();
    }

    return author;
}

In project development, it is recommended to maintain the singleton of httpclient. If you do not do so, instantiate httpclient every request, and a large number of requests will run out of sockets and throw them outSocketExceptionAbnormal.

More exciting, welcome to subscribe

Translation link:https://www.infoworld.com/article/3198673/when-to-use-webclient-vs-httpclient-vs-httpwebrequest.html

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]