.NET: WebBrowser, WebClient, WebRequest, HTTPWebRequest... ARGH!

Maxim Zaslavsky picture Maxim Zaslavsky · Nov 23, 2009 · Viewed 14.2k times · Source

In the System.Net namespace, there are very many different classes with similar names, such as:

  • WebBrowser and WebClient
  • WebRequest and HTTPWebRequest
  • WebResponse and HTTPWebResponse

Those are the main ones I'm curious about.

What is each one's function? How are they different from one another?

Also, in what cases would you use which?

Answer

Ash picture Ash · Nov 23, 2009

WebBrowser is actually in the System.Windows.Forms namespace and is a visual control that you can add to a form. It is primarily a wrapper around the Internet Explorer browser (MSHTML). It allows you to easily display and interact programmatically with a web page. You call the Navigate method passing a web URL, wait for it to complete downloading and display and then interact with the page using the object model it provides.

HttpWebRequest is a concrete class that allows you to request in code any sort of file over HTTP. You usually receive it as a stream of bytes. What you do with it after that is up to your application.

HttpWebResponse allows you to process the response from a web server that was previously requested using HttpWebRequest.

WebRequest and WebResponse are the abstract base classes that the HttpWebRequest and HttpWebResponse inherit from. You can't create these directly. Other classes that inherit from these include Ftp and File classes.

WebClient I have always seen as a nice helper class that provides simpler ways to, for example, download or upload a file from a web url. (eg DownloadFile and DownloadString methods). I have heard that it actually uses HttpWebRequest / HttpWebResponse behind the scenes for certain methods.

If you need more fine grained control over web requests and responses, HttpWebRequest / HttpWebResponse are probably the way to go. Otherwise WebClient is generally simpler and will do the job.