HttpClient Class

System.Net.Http

Provides a base class for sending an HTTP request and receiving an HTTP response as an asynchronous operation.

Introduction

The HttpClient class represents the fundamental component for performing HTTP requests in .NET. It allows you to send various types of HTTP messages, such as GET, POST, PUT, DELETE, etc., and handle the responses efficiently. It's designed to be instantiated once and reused throughout the application's lifetime for optimal performance.

Usage

Simple GET Request

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

public class Example
{
    private static readonly HttpClient client = new HttpClient();

    public static async Task Main(string[] args)
    {
        try
        {
            string responseBody = await client.GetStringAsync("https://www.microsoft.com");
            Console.WriteLine(responseBody.Substring(0, 200)); // Print first 200 chars
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"\nException Caught!");
            Console.WriteLine($"Message :{e.Message} ");
        }
    }
}

Members

Constructors

HttpClient()

public HttpClient()

Initializes a new instance of the HttpClient class with default values. This constructor does not set any default headers or base address.

HttpClient(Uri baseAddress)

public HttpClient(Uri baseAddress)

Initializes a new instance of the HttpClient class with the specified base address. This is useful when you are making multiple requests to the same server.

Properties

DefaultRequestHeaders

public System.Net.Http.Headers.HttpRequestHeaders DefaultRequestHeaders { get; }

This property allows you to configure default headers that will be included in every outgoing HTTP request made by this HttpClient instance. This is useful for setting common headers like `User-Agent` or `Accept-Language`.

Methods

GetAsync(string requestUri)

public Task<HttpResponseMessage> GetAsync(string requestUri)

Sends a GET request to the specified uniform resource identifier (URI) as an asynchronous operation. The returned Task object represents the asynchronous operation. The result of the operation is an HttpResponseMessage.

PostAsync(string requestUri, HttpContent content)

public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)

Sends a POST request to the specified uniform resource identifier (URI) as an asynchronous operation. This method is overloaded to allow sending various types of content.

Dispose()

public void Dispose()

Releases the unmanaged resources that are used by the current instance of the HttpClient class. It is important to call Dispose when you are finished using the HttpClient instance to prevent resource leaks.