http client post async code example
Example 1: c# httpclient postasync stringcontent
private static async Task PostBasicAsync(object content, CancellationToken cancellationToken)
{
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Post, Url))
{
var json = JsonConvert.SerializeObject(content);
using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
{
request.Content = stringContent;
using (var response = await client
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
.ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
}
}
}
}
Example 2: c# HttpResponseMessage postResponse = client.PostAsync
async Task<string> GetResponseString(string text)
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = text;
var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
var contents = await response.Content.ReadAsStringAsync();
return contents;
}