HttpClient.SendAsync Method
Sends an HTTP request to the specified resource and receives an HTTP response from the resource as an asynchronous operation.
Syntax
public virtual Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken
)
Parameters
| Name | Type | Description |
|---|---|---|
request |
HttpRequestMessage | An HttpRequestMessage object with the details of the HTTP request. |
cancellationToken |
CancellationToken | A cancellation token to observe for cancellation requests. |
Returns
A Task object that represents the asynchronous operation. The TResult property of the task object contains an HttpResponseMessage object.
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | The request parameter is null. |
| ObjectDisposedException | The HttpClient object has been disposed. |
| OperationCanceledException | The request was canceled. |
Remarks
The SendAsync method sends an HTTP request to the specified resource and receives an HTTP response from the resource. This is an asynchronous method. You can use the await keyword to suspend the calling method until the task completes.
A common scenario for using SendAsync is to send a request and then process the response:
using (HttpClient client = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://api.example.com/data");
// Add headers, content, etc. to the request as needed
HttpResponseMessage response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
// Process the responseBody
}
else
{
// Handle error
}
}
If you need to send the request using a specific HttpRequestMessage (e.g., to set custom headers or use a specific HTTP method other than the defaults provided by helper methods like GetAsync or PostAsync), SendAsync is the appropriate method to use.
The CancellationToken parameter allows you to cancel the operation. If the token is signaled, the operation will be canceled and an OperationCanceledException will be thrown.