httpclient post json c# code example
Example 1: c# httpclient post json 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: example HttpClient c# Post
public async string Example()
{
var pocoObject = new
{
Name = "John Doe",
Occupation = "gardener"
};
string json = JsonConvert.SerializeObject(pocoObject);
StringContent data = new StringContent(json, Encoding.UTF8, "application/json");
var url = "https://httpbin.org/post";
var client = new HttpClient();
var response = await client.PostAsync(url, data);
string result = await response.Content.ReadAsStringAsync();
client.Dispose();
return result;
}
Example 3: .net httpclient add body
public async string Example()
{
var pocoObject = new
{
Name = "John Doe",
Occupation = "gardener"
};
string json = JsonConvert.SerializeObject(pocoObject);
StringContent data = new StringContent(json, Encoding.UTF8, "application/json");
var url = "https://httpbin.org/post";
var client = new HttpClient();
var response = await client.PostAsync(url, data);
string result = await response.Content.ReadAsStringAsync();
client.Dispose();
return result;
}