Just when I was starting to get used to call WebServices through WSDL – like I showed here and here – I had to call a RESTful API. If you don’t know what I’m talking about you’re like me a week ago. Let’s just say that:
- a WSDL API uses SOAP to exchange XML-encoded data
- a REST API uses HTTP to exchange JSON-encoded data
That’s a whole new paradigm. Instead of GetObject()
and SetObject()
methods you have a single url api/object
that may receive either an HTTP GET
request or an HTTP POST
request.
The .NET framework offers you three different classes to consume REST APIs: HttpWebRequest
, WebClient
, HttpClient
. To worsen your analysis paralysis the open-source community created yet another library called RestSharp
. Fear not, I’ll ease your choice.
In the beginning there was… HttpWebRequest
This is the standard class that the .NET creators originally developed to consume HTTP requests. Using HttpWebRequest
gives you control over every aspect of the request/response object, like timeouts, cookies, headers, protocols. Another great thing is that HttpWebRequest
class does not block the user interface thread. For instance, while you’re downloading a big file from a sluggish API server, your application’s UI will remain responsive.
However, with great power comes great complexity. In order to make a simple GET
you need at least five lines of code; we will see that WebClient
uses just two lines.
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();
The number of ways you can make a mistake with HttpWebRequest
is truly astounding. Only use HttpWebRequest
if you require the additional low-level control that it offers.
WebClient. Simple.
WebClient
is a higher-level abstraction built on top of HttpWebRequest
to simplify the most common tasks. Using WebClient
is potentially slower (on the order of a few milliseconds) than using HttpWebRequest
directly. But that “inefficiency” comes with huge benefits: it requires less code, is easier to use, and you’re less likely to make a mistake when using it. That same request example is now as simple as:
var client = new WebClient();
var text = client.DownloadString("http://example.com/page.html");
Note: the using statements from both examples were omitted for brevity. You should definitely dispose your web request objects properly.
Don’t worry, you can still specify timeouts, just make sure you follow this workaround.
HttpClient, the best of both worlds
HttpClient
provides powerful functionality with better syntax support for newer threading features, e.g. it supports the await
keyword. It also enables threaded downloads of files with better compiler checking and code validation. For a complete listing of the advantages and features of this class make sure you read this SO answer.
The only downfall is that it requires .NET Framework 4.5, which many older or legacy machines might not have.
Wait, a new contestant has appeared!
Since HttpClient
is only available for the .NET 4.5 platform the community developed an alternative. Today, RestSharp
is one of the only options for a portable, multi-platform, unencumbered, fully open-source HTTP client that you can use in all of your applications.
It combines the control of HttpWebRequest
with the simplicity of WebClient
.
Conclusion
HttpWebRequest
for controlWebClient
for simplicity and brevityRestSharp
for both on non-.NET 4.5 environmentsHttpClient
for both + async features on .NET 4.5 environments
28 replies on “WebClient vs HttpClient vs HttpWebRequest”
I think your article might have been stolen: http://www.karthikscorner.com/sharepoint/webrequest-vs-httpwebrequest-vs-webclient-vs-httpclient/
Thank you so much. You’re the 2nd person that notices it. I used https://www.copyscape.com/compare.php and to find 4 whole sections copied, a total of 256 words. Same sentences, same words, same order: disgusting copy.
I have notified the thief to take the article down.
If he does not comply, a shutdown order will be sent to Google.
It’s done, the thief had the decency to remove the post. Ultimately he did the right thing.
Thanks for reporting :)
Cool! Thank you~
Performance-wise HttpClient is better than RestSharp – https://amgadfahmi.wordpress.com/2016/03/06/restsharp-vs-httpclient-performance-benchmark/
You are God! Great article!
good
One small correction – HttpClient is supported on .NET 4.0 or higher via the “Microsoft.Net.Http” NuGet package.
And it is possible to see the progress of a download if you specify HttpCompletionOption.ResponseHeadersRead and read the stream, as described on the CoreFX GitHub repo: github.com/dotnet/corefx/issues/6849
Restsharp thrwing status “0” but while receiving from some google extensions like postman restclient is its working fine.
http://stackoverflow.com/questions/40243156/restsharp-returns-status-0-while-calling-post-method
One of the biggest drawback to HttpClient is the testability of the codebase. It does not support IHttpClient and its almost impossible to test in a clean simple way without using expensive test tools such as TypeMock etc. I would not recommend anyone using HttpClient and purely rely on RestSharp which suites for more than 99% of the cases. Now if it does not suite we have control over the codebase. We just have to implement and perform a pull request in github!
I’d encourage you to look at Flurl.Http. It wraps HttpClient and Json.NET and destroys all other options presented here in terms of simplicity and brevity, while still providing control freaks with extensibility hooks to get at all the underlying APIs. And it solves the testing problem you mention.
Excelente Diogo. Muito obrigado! Continua!
For those who have to use .NET 2.0 for some applications, like me, it’s worth noting that RestSharp is for .NET 3.5 upwards. So for .NET 2.0 it’s WebClient vs HttpWebRequest. The following Stackoverflow answer, http://stackoverflow.com/a/8237452/216440 , mentions that WebClient runs on the UI thread so can block the UI while processing data. HttpWebRequest runs on a different thread so won’t have that problem. Just another thing to take into consideration.
Great article. Clears lot of doubts and clear cut distinction as to why these multiple flavors exist.
When i load the website, the google analytics part is not getting loaded. How to load the same? what we can choose and how to do that?
Need help on this
i need to request http web request to wcf rest service. but i should not wait for responce i should continue my flow. can any one please ans to this
That’s a nice article. I wonder if someone had the same problem as me. I am trying to use HttpClient (windows phone 8.1) to send some data to my backend (using PUT method). I am doing it in a background process, and when I turn off the phone, the HttpClient fails to access the host (getting “Not found”). The background process works fine, and when I turn the phone on, the http request starts working again. Any idea what could be wrong?
It seems all of these clients are very basic. I don’t think any of them even supports GZip decoding? HttpClient doesn’t even send the headers for this :(
I have encountered a post on StackOverflow where it shows that the HttpClient has a memory leak when used in a short-lived object in a long-living app (not able to link from here, but search “HttpClientHandler / HttpClient Memory Leak”). There are ways around this, but does anyone know if this is also an issue for RestSharp?
Thank you!!! I’ll share your post
I appreciate ;)
Wow.. Thank you!!!
Great, quick overview — gave me the background and caught me up quickly. Thanks!
So glad it helped you Sean ;)
I chose RestSharp because of portability, simplicity, and community documentation.
Does RestSharp support SOAP out of the box?
I advise you to check their official documentation at https://github.com/restsharp/RestSharp/wiki or through a google search.