using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace EasyDevCore.Remote.HttpAccess
{
///
///
///
public static class HttpClientRequestExtensions
{
///
/// set the base URL.
///
/// The HTTP client.
/// The base URL.
///
public static HttpClient BaseUrl(this HttpClient httpClient, string baseUrl)
{
httpClient.BaseAddress = new Uri(baseUrl);
return httpClient;
}
///
/// Posts as parameter asynchronous.
///
///
/// The HTTP client.
/// The URL.
/// The data.
/// The cancellation token.
///
public static async Task PostAsParamAsync(this HttpClient httpClient, string url, T data, CancellationToken cancellationToken = default)
{
if (typeof(T).IsArray)
{
StringBuilder sb = new StringBuilder(url);
foreach (var item in data as object[])
{
sb.Append("/" + HttpUtility.UrlEncode(item.ToInvariantString()));
}
return await httpClient.PostAsync(sb.ToString(), (HttpContent)null, cancellationToken).ConfigureAwait(false);
}
else
{
var argValues = data.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
.ToDictionary(p => p.Name, p => p.GetValue(data).ToInvariantString());
var formContent = new FormUrlEncodedContent(argValues); //HttpAccessSetup.UrlEncodedSerializerRequest.Serialize(argValues);
return await httpClient.PostAsync(url, formContent, cancellationToken).ConfigureAwait(false);
}
}
///
/// Gets the asynchronous.
///
///
/// The HTTP client.
/// The URL.
/// The data.
/// The cancellation token.
///
public static async Task GetAsync(this HttpClient httpClient, string url, T data, CancellationToken cancellationToken = default)
{
if (typeof(T).IsArray)
{
var argValues = (data as object[]).Select(v => HttpUtility.UrlEncode(v.ToInvariantString()));
var formContent = string.Join("/", argValues);
return await httpClient.GetAsync(url + "/" + formContent, cancellationToken).ConfigureAwait(false);
}
else
{
var argValues = data.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
.Select(p => $"{p.Name}={HttpUtility.UrlEncode(p.GetValue(data).ToInvariantString())}");
var formContent = string.Join("&", argValues);
return await httpClient.GetAsync(url + "/" + formContent, cancellationToken).ConfigureAwait(false);
}
}
///
/// Returns a string that represents the current object, using CultureInfo.InvariantCulture where possible.
/// Dates are represented in IS0 8601.
///
public static string ToInvariantString(this object obj)
{
// inspired by: http://stackoverflow.com/a/19570016/62600
return
obj == null ? null :
obj is DateTime dt ? dt.ToString("o", CultureInfo.InvariantCulture) :
obj is DateTimeOffset dto ? dto.ToString("o", CultureInfo.InvariantCulture) :
obj is IConvertible c ? c.ToString(CultureInfo.InvariantCulture) :
obj is IFormattable f ? f.ToString(null, CultureInfo.InvariantCulture) :
obj.ToString();
}
}
}