Differences Between System.Net.WebRequest, HttpClient and WebClient in C#

Introduction 

 
In the .NET framework, there are three ways we can consume Rest APIs.
  1. System.Net.WebRequest
  2. WebClient
  3. HttpClient 

System.Net.WebRequest

 
System.Net.WebRequest is an abstract class. The HttpWebRequest class allows you to programmatically make web requests to the HTTP server.
 
The following code snippet shows how we can work with HttpWebRequest.
 
Create a Console Application 
 
File-->New-->Project
 
 
 
Select Console Application and give it some meaningful name, like HttpWebRequest
 
 
After creating a console application, write the code with HttpWebRequest 
 
 
This code shows how to read file contents from a remote webserver using the HttpWebRequest Class.
 

WebClient

 
The System.Net.WebClient class provides a high-level abstraction on top of HttpWebRequest. WebClient is just a wrapper around HttpWebRequest, so it uses HttpWebRequest internally.
 
The WebClient bit slow compared to HttpWebRequest.But is very much less code. we can use WebClient for simple ways to connect and work with HTTP services.
 
Create another Console Application in the existing Solution
 
Right click on solution -->Add-->New Project
 
 
Select the  Console Application and give it the name HttpWebClient
 
 
 Add code for downloading string data from Rest API using WebClient. We can pass optional headers.
 
The following simple code shows we can download string data from Rest APIs
 
 
 

HttpClient

 
HttpClient available .Net framework 4.5 or later versions. The HttpsClient provides functionality that neither the Webclient or HttpWenRequest does.
 
For example, with HttpsClient we can make multiple requests without having to create a new object.
 
Http class makes downloading files on separate threads easier. It is the preferred way to consume HTTP requests unless you have a specific reason not to use it. HttpClient combines the flexibility of HttpWebRequest and WebClient.
 
Create another Console Application in the existing Solution
 
Right click on solution --> Add --> New Project
 
 
Select the console application with the name SystemHttpClient
 
 
To start, we use the async and await keywords.
 
 
HttpClient doesn't support FTP, mocking and testing  HttpClient is easier. All the I/O bound methods in HttpClient are asynchronous, and we can use the same HttpClient instance to make concurrent requests as well.
 
The following code snippet shows how we can work with HttpClient.
 
 
 
Note that when there is an error in the response, HttpClient doesn't throw any error. Rather, it sets the IsSucessStatusCode property to false.
 

Summary

 
Above we described the differences between HttpWebRequest, WebClient, and HttpClient.