This is an implementation of HttpClient Json Post by Action parameter.
Logic:
- It is mainly convenient to pass the url and object (automatically converted to json by Json.Net), and can use Action as a parameter to customize function.
- default timeout is 15 sec , if you want to change the time , it could change timeout parameter value.
Code:
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class Program
{
public static void Main(string[] args)
{
Test().Wait();
}
public static async Task Test()
{
//SuccessExecute
await Execute("https://jsonplaceholder.typicode.com/posts", new { value = "ITWeiHan" }); //Result : {"value": "ITWeiHan","id": 101}
//ErrorExecute
await Execute("https://jsonplaceholder.typicode.com/error404", new { value = "ITWeiHan" }); //Result : Error 404
}
public static async Task Execute(string url, object reqeustBody)
{
await HttpClientHelper.PostByJsonContentTypeAsync(url, reqeustBody
, successFunction: responsebody =>
{
//Your Success Logic
Console.WriteLine("Success");
Console.WriteLine(responsebody);
}, errorFunction: httpRequestException =>
{
//Your Error Solution Logic
Console.WriteLine("Error");
Console.WriteLine(httpRequestException.Message);
}
);
}
}
public static class HttpClientHelper
{
public static async Task PostByJsonContentTypeAsync(string url, object reqeustBody, Action<string> successFunction, Action<HttpRequestException> errorFunction, int timeout = 15)
{
var json = JsonConvert.SerializeObject(reqeustBody);
using (var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(timeout) })
using (var request = new HttpRequestMessage(HttpMethod.Post, url))
using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
{
request.Content = stringContent;
try
{
using (var httpResponseMessage = await client.SendAsync(request))
{
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
var responseBody = await httpResponseMessage.Content.ReadAsStringAsync();
successFunction(responseBody);
}
}
catch (HttpRequestException e)
{
errorFunction(e);
}
}
}
}