C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: In DownloadPageAsync, we use 3 using-statements. This helps improve system resource usage.
Await: We use the await keyword twice. We first call GetAsync and then ReadAsStringAsync. And finally we display the result string.
UsingStringsC# program that uses HttpClient
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static void Main()
{
Task t = new Task(DownloadPageAsync);
t.Start();
Console.WriteLine("Downloading page...");
Console.ReadLine();
}
static async void DownloadPageAsync()
{
// ... Target page.
string page = "http://en.wikipedia.org/";
// ... Use HttpClient.
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
// ... Read the string.
string result = await content.ReadAsStringAsync();
// ... Display the result.
if (result != null &&
result.Length >= 50)
{
Console.WriteLine(result.Substring(0, 50) + "...");
}
}
}
}
Output
Downloading page...
<!DOCTYPE html>
<html lang="en" dir="ltr" class="c...
And: A static HttpClient may work better in some programs. If you run out of system resources with HttpClient, try a static HttpClient.
Note: The "using" statement should usually be used with types that implement IDisposable. But if this causes an error, it can be omitted.
C# program that uses static HttpClient
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static void Main()
{
// Run the task.
Task.Run(new Action(DownloadPageAsync));
Console.ReadLine();
}
static HttpClient _client = new HttpClient();
static async void DownloadPageAsync()
{
// Use static HttpClient to avoid exhausting system resources for network connections.
var result = await _client.GetAsync("http://www.example.com/");
// Write status code.
Console.WriteLine("STATUS CODE: " + result.StatusCode);
}
}
Output
STATUS CODE: OK
Note: With WebClient, its "Async" method uses an object token. This is more clumsy.
WebClientTherefore: If async and await are used in the program, the HttpClient is preferable—it gains compiler checking and improved syntax.
Note: Thanks to Nedim Ibrahimkadic for the helpful information about reusing a single HttpClient.