using System.Text; using System.Text.Json; using System.IdentityModel.Tokens.Jwt; using ServerCore; using ServerBase; namespace ServerBase; public static class HttpClientHelper { public static async Task<(bool, string)> sendHttpRequest( string httpMethod , string url , string? jwt , string? bodyJson , string mediaType , string userAgentName , string userAgentVersion , short timeOutSec = 5 ) { validateUserAgentArgs(mediaType, userAgentName, userAgentVersion); Log.getLogger().debug($"Request Message To WebServer. url : {url}, httpMethod : {httpMethod}, jwt : {jwt}, bodyJson : {bodyJson}"); var requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), url); if (!string.IsNullOrEmpty(jwt)) { requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", jwt); } if (!string.IsNullOrEmpty(bodyJson)) { requestMessage.Content = new StringContent(bodyJson, Encoding.UTF8, mediaType); } requestMessage.Headers.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue(userAgentName, userAgentVersion)); try { using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeOutSec))) { var resMsg = await SharedHttpClient.It.sendAsync(requestMessage, cts.Token); if (resMsg == null) { Log.getLogger().error($"resMsg is null, sendAsync() returned null - url:{url}"); return (false, string.Empty); } var readMsg = await resMsg.Content.ReadAsStringAsync(); Log.getLogger().debug($"Response Message From sendAsync() : readMsg:{readMsg} - url:{url}"); if (!resMsg.IsSuccessStatusCode) { return (false, readMsg); } return (true, readMsg); } } catch (OperationCanceledException e) { Log.getLogger().error($"OperationCanceledException !!!, Request timed out !!! : exception:{e} - url:{url}"); return (false, "Request Timeout"); } catch (Exception e) { Log.getLogger().error($"Exception !!!, Failed to perform in sendHttpRequest() : exception:{e} - - url:{url}"); return (false, string.Empty); } } private static void validateUserAgentArgs(string mediaType, string userAgentName, string userAgentVersion) { if (mediaType.isNullOrWhiteSpace()) throw new ArgumentException("mediaType must be a non-empty string.", nameof(mediaType)); if (userAgentName.isNullOrWhiteSpace()) throw new ArgumentException("userAgentName must be a non-empty string.", nameof(userAgentName)); if (userAgentVersion.isNullOrWhiteSpace()) throw new ArgumentException("userAgentVersion must be a non-empty string.", nameof(userAgentVersion)); } }