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

Viewed 14506

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?

4 Answers

WebClient is quite a neat way to fetch the HTML page. Here is the code snippet to download a response string.

   string getHtmlPageUsingWC(string strQuery, System.Net.WebProxy proxy = null)
    {
        string strResponse = String.Empty;
        using (WebClient wc = new WebClient())
        {
            wc.Encoding = Encoding.UTF8;
            IWebProxy wp = WebRequest.DefaultWebProxy;
            wp.Credentials = CredentialCache.DefaultCredentials;
            wc.Proxy = wp;
            wc.Headers.Add("Accept-Language:en");

            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("q", strQuery);

            wc.QueryString.Add(nvc);

            try
            {
                strResponse = wc.DownloadString(m_strURL);
            }
            catch (Exception ex)
            {
                strResponse = "Request Declined: " + ex.Message;
                Console.WriteLine(ex.Message);
            }
        }

        return strResponse;
    }
Related