Sends an HTTP request to the specified resource and receives the HTTP response from the resource as an asynchronous operation.
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
HttpRequestMessageCancellationTokenCancellationToken.None.
Task<HttpResponseMessage>Result property on the task object returns an HttpResponseMessage containing the response from the server.
ArgumentNullException: The request parameter is null.ObjectDisposedException: The HttpClient instance has been disposed.InvalidOperationException: The request message is invalid or the HttpClient is already in use for another asynchronous operation.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.
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}");
}
}
}
}