The .NET Framework provides 3 classes for making HTTP requests. From oldest to newest, they are:
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.
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.