C# - 3 ways to make an HTTP GET request

The .NET Framework provides 3 classes for making HTTP requests. From oldest to newest, they are:

  1. WebRequest Obsolete. Don't use.
  2. WebClient Use this class if you aren't on Framework 4.5
  3. HttpClient Use this class if you are on Framework 4.5 or later.

1 Using System.Net.WebRequest

public static string HttpGet(string uri)
{
    string content = null;
 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
 
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using (Stream stream = response.GetResponseStream())
    using (StreamReader sr = new StreamReader(stream))
    {
        content = sr.ReadToEnd();
    }
 
    return content;
}

Supports multiple protocols. WebRequest is an abstract base class with 4 derived classes, one for each supported protocol. Provides a high degree of customization and control.

HttpWebRequest for http://
FtpWebRequest for ftp://
FileWebRequest for file://
PackWebRequest for pack://

Availability: .NET Framework 1.1 and later. Made obsolete in .NET Framework 4.5.

2 Using System.Net.WebClient

public static string HttpGet(string uri)
{
    string content = null;
 
    var wc = new WebClient();
    content = wc.DownloadString(uri);
 
    return content;
}

A high level wrapper around WebRequest. It simplifies many common operations.

Availability: .NET Framework 1.1 and later.

3 Using System.Net.Http.HttpClient

public async static Task<string> HttpGetAsync(string uri)
{
    string content = null;
 
    var client = new HttpClient();
    var response = await client.GetAsync(uri);
    if (response.IsSuccessStatusCode)
    {
        content = await response.Content.ReadAsStringAsync();
    }
 
    return content;
}

The newest HTTP class from Microsoft. Supports the await keyword. All methods are asynchronous.

Availability: .NET Framework 4.5 and later.


Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath