91 lines
2.8 KiB
C#
91 lines
2.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Net.Http;
|
|
using Newtonsoft.Json;
|
|
|
|
namespace LCU.Library.Internal.CoreApiWrapperLib.Utilities
|
|
{
|
|
public static class HttpUtilities
|
|
{
|
|
private const int ParamCounterDefault = 1;
|
|
|
|
public static HttpClient GetClient(Uri uri)
|
|
{
|
|
var handler = new HttpClientHandler
|
|
{
|
|
SslProtocols = System.Security.Authentication.SslProtocols.Tls12 |
|
|
System.Security.Authentication.SslProtocols.Tls11 |
|
|
System.Security.Authentication.SslProtocols.Tls,
|
|
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
|
|
};
|
|
|
|
var httpClient = new HttpClient(handler)
|
|
{
|
|
Timeout = TimeSpan.FromSeconds(60),
|
|
BaseAddress = uri
|
|
};
|
|
return httpClient;
|
|
}
|
|
|
|
public static Uri BuildHttpsUri(string hostName, string endpoint)
|
|
{
|
|
return new Uri($"https://{hostName}{endpoint}");
|
|
}
|
|
|
|
public static string BuildEndPointWithParams(string endpoint, Dictionary<string, string> parameters)
|
|
{
|
|
if(parameters == null || parameters.Count < 0)
|
|
{
|
|
return endpoint;
|
|
}
|
|
|
|
var counter = ParamCounterDefault;
|
|
foreach (var key in parameters.Keys)
|
|
{
|
|
var splitter = counter == ParamCounterDefault ? "?" : "&";
|
|
endpoint = $"{endpoint}{splitter}{key}={parameters[key]}";
|
|
counter++;
|
|
}
|
|
|
|
return endpoint;
|
|
}
|
|
|
|
public static string ReplaceRootParameter(string endpoint, string placeholder, string value)
|
|
{
|
|
return endpoint.Replace(placeholder, value);
|
|
}
|
|
|
|
public static Dictionary<string, string> BuildDictionaryOfNonNullValues<T>(T model)
|
|
{
|
|
var bodyParams = new Dictionary<string, string>();
|
|
var modelType = typeof(T);
|
|
var properties = modelType.GetProperties();
|
|
|
|
foreach (var property in properties)
|
|
{
|
|
var fieldValue = model.GetType().GetProperty(property.Name).GetValue(model, null);
|
|
if (fieldValue != null)
|
|
{
|
|
bodyParams.Add(property.Name, fieldValue.ToString());
|
|
}
|
|
}
|
|
|
|
return bodyParams;
|
|
}
|
|
|
|
public static string BuildJsonOfNonNullProperties<T>(T model)
|
|
{
|
|
var bodyParams = BuildDictionaryOfNonNullValues(model);
|
|
|
|
if (bodyParams.Count <= 0)
|
|
{
|
|
return "";
|
|
}
|
|
|
|
return JsonConvert.SerializeObject(bodyParams);
|
|
}
|
|
|
|
|
|
}
|
|
}
|