3
\$\begingroup\$

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);
            }
        }
    }
}
\$\endgroup\$
5
\$\begingroup\$

Great job. Here are some minor notes though.

In newer versions of C# you can leverage async Main in order not to wait for your test method.

public static async Task Main(string[] args)
{
    await Test();
}

You can speed things up a bit with executing your tests in parallel

public static async Task Test()
{
    var successExecute = Execute("https://jsonplaceholder.typicode.com/posts", new { value = "ITWeiHan" }); //Result : {"value": "ITWeiHan","id": 101}
    var errorExecute = Execute("https://jsonplaceholder.typicode.com/error404", new { value = "ITWeiHan" }); //Result : Error 404
    await Task.WhenAll(successExecute, errorExecute);
}

Also, PostByJsonContentTypeAsync throws couple of more exceptions. Namely InvalidOperationException and ArgumentNullExceptions. Are you intentionally not handling them?

\$\endgroup\$
  • \$\begingroup\$ thanks , yes , i only Focus on HttpRequestException ,user can edit exception class lilke Exception. \$\endgroup\$ – IT WeiHan Oct 11 at 2:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.