Working with HTTP in .NET

The .NET Framework provides a robust set of classes for interacting with the Hypertext Transfer Protocol (HTTP). These classes allow you to send HTTP requests and receive HTTP responses, enabling communication with web servers and APIs.

Key Classes and Concepts

  • HttpClient: The primary class for sending HTTP requests. It's recommended to reuse a single instance of HttpClient for the lifetime of your application to leverage connection pooling and reduce overhead.
  • HttpRequestMessage: Represents an HTTP request to be sent. You can configure its content, headers, and method (e.g., GET, POST, PUT, DELETE).
  • HttpResponseMessage: Represents an HTTP response received from a server. It contains status codes, headers, and the response body.
  • HttpContent: Represents the content of an HTTP message (request or response body). Common implementations include StringContent and ByteArrayContent.
  • URI Handling: The System.Uri class is used for parsing and manipulating Uniform Resource Identifiers.

Sending an HTTP GET Request

Here's a simple example of how to perform an HTTP GET request using HttpClient:

C# Example


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

public class HttpExample
{
    public static async Task Main(string[] args)
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                string url = "https://jsonplaceholder.typicode.com/todos/1";
                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode(); // Throws if the status code is an error

                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Response:");
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request error: {e.Message}");
            }
        }
    }
}
                    

Sending an HTTP POST Request

To send data with a POST request, you'll typically create an HttpContent object:

C# Example


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

public class HttpPostExample
{
    public static async Task Main(string[] args)
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                string url = "https://jsonplaceholder.typicode.com/posts";
                string jsonPayload = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
                HttpContent content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await client.PostAsync(url, content);
                response.EnsureSuccessStatusCode();

                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Response:");
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request error: {e.Message}");
            }
        }
    }
}
                    

HTTP Headers

You can customize request and response headers:

  • Request Headers: Use client.DefaultRequestHeaders or add headers to individual HttpRequestMessage instances.
  • Response Headers: Access headers via the response.Headers property.

Advanced Scenarios

The HttpClient class supports various advanced features, including:

  • Custom HTTP methods (PUT, DELETE, etc.)
  • Authentication (Basic, Bearer tokens)
  • Timeouts and cancellation
  • Handling redirects
  • Working with different content types (XML, form data)

For detailed information on specific methods and properties, please refer to the official HttpClient documentation.