HttpClient.PostAsync Method
Asynchronously sends an HTTP POST request to the specified URI. This method does not block the calling thread.
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(
string requestUri,
System.Net.Http.HttpContent? content
);
Parameters
| Name | Type | Description |
|---|---|---|
requestUri |
string |
The URI to send the POST request to. |
content |
System.Net.Http.HttpContent? |
The HTTP content to send as the body of the POST request. This can be null. |
Returns
The Task<HttpResponseMessage> object that represents the asynchronous operation. The task result contains the HttpResponseMessage.
Exceptions
ArgumentNullException: TherequestUriorcontentis null.InvalidOperationException: TheHttpClientinstance has been disposed.HttpRequestException: An error occurred during the execution of the HTTP request.
Example
The following example demonstrates how to send a POST request with JSON content.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
public class Example
{
private static readonly HttpClient client = new HttpClient();
public static async Task Main(string[] args)
{
string apiUrl = "https://api.example.com/data";
var postData = new { name = "John Doe", age = 30 };
var jsonContent = new StringContent(JsonSerializer.Serialize(postData), Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(apiUrl, jsonContent);
response.EnsureSuccessStatusCode(); // Throws if the status code is not a success code
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Response: {responseBody}");
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
}
}
Important: It is recommended to reuse a single
HttpClient instance throughout the application's lifetime. Creating new instances for each request can lead to socket exhaustion.
Overloads
This method has several overloads to accommodate different scenarios, including sending a request with a cancellation token.