.Net Asp.Net MVC C# Development

Consuming API and WebClient vs. HttpClient vs. HttpWebRequest

In a nutshell, WebRequest—in its HTTP-specific implementation, HttpWebRequest—represents the original way to consume HTTP requests in .NET Framework. WebClient provides a simple but limited wrapper around HttpWebRequest. And HttpClient is the new and improved way of doing HTTP requests and posts, having arrived with .NET Framework 4.5.

System.Net.WebRequest

The System.Net.WebRequest class is an abstract class. Thus you will need to create a HttpWebRequest or FileWebRequest to consume HTTP requests using this class. The following code snippet shows how you can work with WebRequest.

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

System.Net.HttpWebRequest

WebRequest was the first class provided in the .NET Framework to consume HTTP requests. It gives you a lot of flexibility in handling each and every aspect of the request and response objects, without blocking the user interface thread. You can use this class to access and work with headers, cookies, protocols, and timeouts when working with HTTP. The following code snippet illustrates how HttpWebRequest can be 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();

System.Net.WebClient

The System.Net.WebClient class in .NET provides a high-level abstraction on top of HttpWebRequest. WebClient is just a wrapper around HttpWebRequest, so uses HttpWebRequest internally. Thus WebClient is a bit slow compared to HttpWebRequest, but requires you to write much less code. You can use WebClient for simple ways to connect to and work with HTTP services. It is generally a better choice than HttpWebRequest unless you need to leverage the additional features that HttpWebRequest provides. The following code snippet shows how you can work with WebClient.

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

System.Net.Http.HttpClient

HttpClient was introduced in .NET Framework 4.5. For developers using .NET 4.5 or later, it is the preferred way to consume HTTP requests unless you have a specific reason not to use it. In essence, HttpClient combines the flexibility of HttpWebRequest and the simplicity of WebClient, giving you the best of both the worlds.

The HttpWebRequest class provides a lot of control over the request/response object. However, you should be aware that HttpClient was never designed to be a replacement for WebClient. You should use HttpWebRequest instead of HttpClient whenever you need the additional features that HttpWebRequest provides. Further, unlike WebClient, HttpClient lacks support for progress reporting and custom URI schemes. 

Although HttpClient doesn’t support FTP, mocking and testing HttpClient is easier. All I/O bound methods in HttpClient are asynchronous, and you can use the same HttpClient instance to make concurrent requests as well. The following code snippet illustrates how you can work with 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;
}

Note that when there is an error in the response, HttpClient doesn’t throw an error. Rather, it sets the IsSuccessStatusCode property to false. If you want to throw an exception if the IsSuccessStatusCode property is false, you can make a call to the EnsureSuccessStatusCode method on the response instance as shown below.

response.EnsureSuccessStatusCode();

HttpClient was designed to be instantiated once and reused throughout the application’s lifecycle—you should not create a new HttpClient instance for every request that your application needs to process. If you do, the available sockets could become exhausted by heavy traffic, resulting in SocketException errors. The recommended practice is to create a single, shared HttpClient instance.

Leave a Reply

Your email address will not be published. Required fields are marked *