MaxBeauchemin
1/3/2018 - 2:28 PM

HTTP Post

Call RESTful web services with this flexible POST format

using System.Net.Http;
using Newtonsoft.Json;

public static Response<T> Post<T, V> (string endpoint, V body, bool throwExceptionOnFail = false, HTTPAuthentication authentication = null, bool parseResponse = true)
{
    var response = new Response<T> { Success = true };

    try
    {
        if (string.IsNullOrWhiteSpace(endpoint))
        {
            throw new Exception(string.Format(ResourceDomain.XCannotBeNullOrEmpty, "endpoint"));
        }

        var httpClient = new HttpClient();

        var request = new HttpRequestMessage(HttpMethod.Post, new Uri(endpoint))
        {
            Content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json")
        };

        if (authentication != null)
        {
            var byteArray = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", authentication.User, authentication.Password));
            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
        }

        var httpResponse = httpClient.SendAsync(request).Result;
        if (httpResponse.IsSuccessStatusCode)
        {
            if (parseResponse)
            {
                var res = httpResponse.Content.ReadAsStringAsync();
                response.Value = JsonConvert.DeserializeObject<T>(res.Result);
            }
        }
        else
        {
            throw new Exception(string.Format(ResourceDomain.HTTPError, httpResponse.StatusCode, httpResponse.ReasonPhrase));
        }
    }
    catch (Exception ex)
    {
        response.Success = false;
        response.Message = ex.Message;

        if (throwExceptionOnFail)
        {
            throw ex;
        }
    }

    return response;
}