Sending an HTTP request

How to:

C# makes sending HTTP requests straightforward with HttpClient. Here’s the skeleton of a GET request:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
    static async Task Main(string[] args)
        using HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync("http://example.com");
        string responseBody = await response.Content.ReadAsStringAsync();

Sample output (truncated):

<!doctype html>
    <title>Example Domain</title>

Deep Dive

HttpClient was introduced in .NET Framework 4.5 to make HTTP communication easier. Before that, you’d likely have to wrestle with HttpWebRequest and HttpWebResponse classes, which were more cumbersome.

There are other ways to send HTTP requests in C#. RestSharp and Flurl are two popular third-party libraries offering a more fluent interface and extra features. But HttpClient is usually more than enough for most needs.

Implementation wise, HttpClient is designed to be reused for multiple requests. Instantiating it for each request can exhaust the number of sockets available under heavy loads. Always, and I mean always, pay attention to proper disposal of HttpClient instances to avoid resource leaks.

See Also