In this quick tutorial we’ll explore diffrent HTTP clients API provided by C# and .NET platforms.
1 – Introduction
HTTP short for Hypertext Transfer Protocol, is a high level protocol (application layer) used for communication between network nodes following client-server archirecture. HTTP is a stateless protocol, meaning that each request message can be understood in isolation by the server and it does not store any state about the client session (state is therefore kept entirely on the client). This makes HTTP servers easy to design, light and and more suited to crashs since they don’t have to resore any state. A browser and website are respectively examples of HTTP client and server.
REST, Representational state transfer, is a software architectural style that defines a set of constraints to be used for creating Web services, called RESTful Web services. They allow the requesting systems to access and manipulate textual representations of Web resources by using a uniform and predefined set of stateless operations.
Let’s say that a REST API uses HTTP protocol to exchange JSON-encoded data. There are other kinds of Web services, such as WSDL API (aka SOAP Web services) that expose their own arbitrary sets of operations and uses SOAP to exchange XML-encoded data.
2 – Create HTTP clients
As we know we can consider a browser as HTTP client that can request a page in the internet using its URL. You can alos create a request (generally asynchronous) using Javascript to request data from a server.
C# provides different API to create requests and consume HTTP services.
– HttpWebRequest
– WebClient
– HttpClient
And an open source option
– RestSharp
2.1 – HttpWebRequest
- Oldest library to consume HTTP requests (compatible with oldest versions of .NET).
- Low-level control, control over every aspect of the request/response object (timeouts, cookies, headers, protocols, etc.).
- Does not block the user interface thread (UI remain responsive while waiting for response).
- Great complexity and lot of code in order to make a simple operation (mistakes, issues, etc.).
HttpWebRequest http = (HttpWebRequest)WebRequest.Create("http://example.com");
WebResponse response = http.GetResponse();
MemoryStream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
string content = sr.ReadToEnd();
2.2 – WebClient
- High-level abstraction, simple and easy to use
- Available in older versions of .NET
- Low-level control like timeouts is possible
- Provides synchronous and asynchronous methodes
- Potentially slower than HttpWebRequest (built on top of it)
- Difficult to mock and test
var client = new WebClient();
var text = client.DownloadString("http://example.com/page.html");
2.3 – HttpClient
- Available on .NET 4.5 or higher
- Better syntax and support for newer threading features
- Can reuse resolved DNS, cookie configuration and other authentication
- Single instance to make concurrent requests
- Easy to mock and test
- All methods are asynchronous
var client = new HttpClient();
HttpResponseMessage result = await client.GetAsync("http://example.com");
2.4 – HttpClient and IHttpClientFactory
Note that the use of HTTP clients (like HttpClient) in C # must respect some guidelines when instanciating and destroying them (singleton, disposing, etc.). In .NET Core 2.1 IHttpClientFactory is introduced to be used for creating HttpClient in a safer way. You can learn more about it by reading Use IHttpClientFactory to implement resilient HTTP requests or using HttpClientHandler.
From microsoft documentation,
HttpClient is intended to be instantiated once and reused throughout the life of an application. […]. If you instantiate an HttpClient class for every request, the number of sockets available under heavy loads will be exhausted. This exhaustion will result in SocketException errors.
In brief, HttpClient implements IDisposable but disposing it won’t be a good thing ! It uses a connection pool (sockets, etc.), disposing it, means you’ll instanciate it again and every instance will use a socket that won’t be closed after a dispose !
3 – Conclusion
Use HttpWebRequest for control and WebClient for simplicity. RestSharp is a good open-source option that combines control and simplicity for all .NET environments. Finally, HttpClient available in >= .NET 4.5 environments and provides all the features mentioned above and more suited for async.
Note : don’t forget to dispose properly or wrap those created HTTP clients with using statement.
References
Exam Ref 70-483 Programming in C#, 2nd Edition
WebClient vs HttpClient vs HttpWebRequest
Should … be singleton or new for every request
HttClient – Instancing
You’re using HttpClient wrong
