The best VPN 2024

The Best VPS 2024

The Best C# Book

How to choose WebClient HttpClient HttpWebRequest in .NET

Spread the love

How to choose WebClient HttpClient HttpWebRequest in .NET? When we use .NET to call RestAPI, there are usually three choices, namely: WebClient, HttpWebRequest,HttpClient.

How to choose WebClient HttpClient HttpWebRequest in .NET
How to choose WebClient HttpClient HttpWebRequest in .NET

How to choose WebClient HttpClient HttpWebRequest

In this article, we will discuss how to use these three methods to call RestAPI, and I will also provide corresponding code examples to help you better understand The concepts and usage of these three, in simple terms:

  • HttpWebRequest It is a relatively low-level way of handling Http request/response.
  • WebClient Provides a high-level encapsulation of HttpWebRequest to simplify the user’s call.
  • HttpClient It is a new toolkit for processing Http request/response with higher performance.

Next we discuss abstract classes WebRequest.

WebRequest

WebRequest is based on a specific http implementation, which is an abstract class, so when processing Reqeust requests, the bottom layer will generate corresponding subclasses based on the url passed in, 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();

How to choose WebClient HttpClient HttpWebRequest

WebRequest .NET Framework is the first class Http request for processing, the processing Http Request and Response providing a lot of flexibility to the caller, you can use this class to access the headers, cookies, protocols timeouts and the like, the following The 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();

How to choose WebClient HttpClient HttpWebRequest

WebClient

WebClient is a high-level encapsulation of HttpWebRequest. It provides callers with a more convenient way to use. Of course, the sacrifice is that the performance of WebClient is slightly inferior to HttpWebRequest. If your business scenario is simply to access a third-party Http Service, then I suggest You use WebClient. Similarly, if you have more refined configuration, use HttpWebRequest. The following code shows how to use WebClient.

string data = null;

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

How to choose WebClient HttpClient HttpWebRequest

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 use HttpClient first. In essence, HttpClient is a later product, it absorbs Because of the flexibility of HttpWebRequest and the convenience of WebClient, HttpClient is currently the best choice.

In HttpWebRequest request/response provided on the object a very fine configuration, but you have to pay attention to the emergence of HttpClient not intended to replace WebClient, the implication is that HttpClient has its drawbacks, such as: can not provide schedule processing and URI custom made advantages, does not support FTP and so on, there are a lot of HttpClient , All its IO operation methods are asynchronous, of course, if there are special reasons, you can also use the synchronous method. The following code shows how to use HttpClient.

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

How to choose WebClient HttpClient HttpWebRequest

It is noteworthy that when the response error occurs, by default HttpClient does not throw an exception if you are certain requirements HttpClient throw an exception in this case, can be changed IsSuccessStatusCode = false to alter this default behavior, the practice is to call response.EnsureSuccessStatusCode();.

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

    HttpResponseMessage response = await client.GetAsync(uri);

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

    return author;
}

How to choose WebClient HttpClient HttpWebRequest

In project development, the recommended practice is to maintain a single HttpClient example of, if you do not do so, each request Request instantiated once HttpClient, then the large number of requests will run out of your socket and throw SocketException an exception.

Leave a Comment