What difference is there between WebClient and HTTPWebRequest classes in .NET?

GurdeepS picture GurdeepS · Feb 14, 2011 · Viewed 175.4k times · Source

What difference is there between the WebClient and the HttpWebRequest classes in .NET? They both do very similar things. In fact, why weren't they merged into one class (too many methods/variables etc may be one reason but there are other classes in .NET which breaks that rule).

Thanks.

Answer

John Sheehan picture John Sheehan · Feb 14, 2011

WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:

var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

With WebClient, you just do DownloadString:

var client = new WebClient();
var content = client.DownloadString("http://example.com");

Note: I left out the using statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.

In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.