HttpClient.SendAsync Method

Sends an HTTP request to the specified resource and receives the HTTP response from the resource as an asynchronous operation.

Syntax

public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)

Parameters

Returns

Exceptions

Remarks

The SendAsync method is the primary method for sending HTTP requests with the HttpClient class. It allows for a high degree of customization through the HttpRequestMessage object, including setting headers, content, and the HTTP method.

It is recommended to reuse a single instance of HttpClient for the lifetime of an application. Creating new instances for each request can lead to socket exhaustion and performance issues.

Example


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

public class Example
{
    public static async Task Main(string[] args)
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                // Create an HttpRequestMessage
                var request = new HttpRequestMessage(HttpMethod.Get, "https://api.example.com/data");
                request.Headers.Add("Accept", "application/json");

                // Send the request asynchronously
                HttpResponseMessage response = await client.SendAsync(request);

                // Ensure the response was successful
                response.EnsureSuccessStatusCode();

                // Read the response content
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request exception: {e.Message}");
            }
            catch (TaskCanceledException e)
            {
                Console.WriteLine($"Request timed out or was cancelled: {e.Message}");
            }
        }
    }
}
            

See Also