HttpClient.SendAsync Method
Sends an HTTP request to a server and receives a response as an asynchronous operation.
public Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken
);
HttpRequestMessage request,
CancellationToken cancellationToken
);
Parameters
-
request: HttpRequestMessage
The HTTP request message to send. -
cancellationToken: CancellationToken
A token to observe for cancellation requests.
Returns
Task<HttpResponseMessage>: The HTTP response received from the server.
Note: This method is the fundamental way to send HTTP requests using
HttpClient. It supports a wide range of HTTP methods and configurations.
Remarks
The SendAsync method sends an HTTP request to a server and returns a Task<HttpResponseMessage> object that represents the asynchronous operation.
When the asynchronous operation completes, the result is an HttpResponseMessage object that contains the HTTP response from the server.
It is important to dispose of the HttpResponseMessage object when you are finished with it to release resources.
Example
The following example shows how to send a GET request and process the response:
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public class HttpClientExample
{
public static async Task Main()
{
using (var client = new HttpClient())
{
try
{
var request = new HttpRequestMessage(
HttpMethod.Get,
"https://jsonplaceholder.typicode.com/todos/1");
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode(); // Throws an exception if the status code is not successful
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}
catch (HttpRequestException e)
{
Console.WriteLine($"\nException Caught!");
Console.WriteLine($"Message :{0} ", e.Message);
}
}
}
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public class HttpClientExample
{
public static async Task Main()
{
using (var client = new HttpClient())
{
try
{
var request = new HttpRequestMessage(
HttpMethod.Get,
"https://jsonplaceholder.typicode.com/todos/1");
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode(); // Throws an exception if the status code is not successful
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}
catch (HttpRequestException e)
{
Console.WriteLine($"\nException Caught!");
Console.WriteLine($"Message :{0} ", e.Message);
}
}
}
Important: Always ensure that you dispose of the
HttpClient instance when you are finished with it. It is recommended to use it for a single, long-lived HttpClient instance for the lifetime of an application. Creating a new HttpClient for every request can lead to socket exhaustion.
Tip: For more complex scenarios, consider using
HttpClientFactory for managing HttpClient instances.