using LCU.Library.Internal.Exceptions; using Newtonsoft.Json; using Serilog; using System; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; using JsonSerializer = System.Text.Json.JsonSerializer; namespace LCU.API.Internal.DocumentLib.Utilities; public class HttpUtilities { public static HttpClient CreateClient(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 async Task PostAsync(Uri uri, TRequest request) { try { var client = CreateClient(uri); var jsonBody = JsonSerializer.Serialize(request); var content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); var response = await client.PostAsync(uri, content); if (!response.IsSuccessStatusCode) { throw new ServiceException($"StatusCode:{response.StatusCode}, " + $"Content: {response.Content.ReadAsStringAsync().Result}"); } } catch (Exception exception) { Log.Error(exception, "Failure during PostAsync."); throw new ServiceException($"Failure during Document Upload. Exception Message: {exception.Message}"); } } public static async Task PostAsync(Uri uri, TRequest request) { try { var client = CreateClient(uri); var jsonBody = JsonSerializer.Serialize(request); var content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); var response = await client.PostAsync(uri, content); if (!response.IsSuccessStatusCode) { throw new ServiceException($"StatusCode:{response.StatusCode}, " + $"Content: {response.Content.ReadAsStringAsync().Result}"); } var stringResponse = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize(stringResponse, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); } catch (Exception exception) { Log.Error(exception, "Failure during PostAsync."); throw new ServiceException($"Failure during PostAsync. Exception Message: {exception.Message}"); } } public static async Task GetAsync(string url) { try { var uri = new Uri(url); var client = CreateClient(uri); var response = await client.GetAsync(uri); if (!response.IsSuccessStatusCode) { throw new ServiceException($"StatusCode:{response.StatusCode}, " + $"Content: {response.Content.ReadAsStringAsync().Result}"); } var stringResponse = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize(stringResponse, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); } catch (Exception exception) { Log.Error(exception, "Failure during GetAsync."); throw new ServiceException($"Failure during GetAsync. Exception Message: {exception.Message}"); } } }