using SqlSugar; using System.Text; using System.Text.Json; using WIDESEAWCS_Code; using WIDESEAWCS_Core.Helper; namespace WIDESEAWCS_Core.Http { public static class HttpRequestHelper { /// /// Òì²½·¢ËÍHTTPÇëÇó²¢·µ»ØÏìÓ¦ÄÚÈÝ /// /// ÇëÇóµØÖ· /// ÇëÇó·½·¨ /// ÇëÇóÄÚÈÝ /// ÄÚÈÝÀàÐÍ /// ³¬Ê±Ê±¼ä£¨Ã룩 /// ÇëÇóÍ· /// ÏìÓ¦ÄÚÈÝ public static async Task SendAsync(string serviceAddress, HttpMethod method, string? requestContent = null, string contentType = "application/json", int timeOut = 60, Dictionary? headers = null) { using HttpClient httpClient = new HttpClient(); httpClient.Timeout = new TimeSpan(0, 0, timeOut); using HttpRequestMessage request = new HttpRequestMessage(method, serviceAddress); if (!string.IsNullOrWhiteSpace(requestContent)) { request.Content = new StringContent(requestContent, Encoding.UTF8, contentType); } if (headers != null) { foreach (var header in headers) { request.Headers.TryAddWithoutValidation(header.Key, header.Value); } } using HttpResponseMessage response = await httpClient.SendAsync(request); string result = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { throw new Exception($"Òì³££¬ÏìÓ¦Â룺{(int)response.StatusCode},Ô­Òò£º{response.ReasonPhrase}"); } return result; } /// /// Òì²½·¢ËÍHTTP GETÇëÇó²¢·µ»ØÏìÓ¦ÄÚÈÝ /// public static Task GetAsync(string serviceAddress, int timeOut = 60, Dictionary? headers = null) { return SendAsync(serviceAddress, HttpMethod.Get, null, "application/json", timeOut, headers); } /// /// Òì²½·¢ËÍHTTP POSTÇëÇó²¢·µ»ØÏìÓ¦ÄÚÈÝ /// public static Task PostAsync(string serviceAddress, string? requestJson = null, string contentType = "application/json", int timeOut = 60, Dictionary? headers = null) { return SendAsync(serviceAddress, HttpMethod.Post, requestJson, contentType, timeOut, headers); } /// /// Òì²½·¢ËÍHTTP PUTÇëÇó²¢·µ»ØÏìÓ¦ÄÚÈÝ /// public static Task PutAsync(string serviceAddress, string? requestJson = null, string contentType = "application/json", int timeOut = 60, Dictionary? headers = null) { return SendAsync(serviceAddress, HttpMethod.Put, requestJson, contentType, timeOut, headers); } /// /// Òì²½·¢ËÍHTTP DELETEÇëÇó²¢·µ»ØÏìÓ¦ÄÚÈÝ /// public static Task DeleteAsync(string serviceAddress, int timeOut = 60, Dictionary? headers = null) { return SendAsync(serviceAddress, HttpMethod.Delete, null, "application/json", timeOut, headers); } /// /// ¸ù¾ÝÊý¾Ý¿âÅäÖ÷¢ËÍHTTPÇëÇó²¢·µ»ØÏìÓ¦ÄÚÈÝ /// /// ÇëÇóÄÚÈÝ /// ÇëÇó·½·¨ /// ÅäÖ÷ÖÀà /// ÅäÖÃÏî /// ÄÚÈÝÀàÐÍ /// ³¬Ê±Ê±¼ä£¨Ã룩 /// ÏìÓ¦ÄÚÈÝ public static async Task SendAsync(string? requestContent, HttpMethod method, string? category, string? configKey, string contentType = "application/json", int timeOut = 60) { ISqlSugarClient? db = App.GetService(); if (db == null) { throw new InvalidOperationException("Êý¾Ý¿â·þÎñδ³õʼ»¯"); } var configs = await db.Ado.SqlQueryAsync( "SELECT * FROM Sys_Config WHERE Category = @Category", new { Category = category }); if (configs.IsNullOrEmpty()) { throw new Exception($"δÕÒµ½ÅäÖ÷ÖÀࣺ{category}"); } string address = string.Empty; string servicePath = string.Empty; Dictionary configDict = new Dictionary(); foreach (var config in configs) { if (config.CategoryItem == "Header") { configDict[config.ConfigKey] = config.ConfigValue; continue; } if (config.ConfigKey == "BASE") { address = config.ConfigValue; continue; } if (!string.IsNullOrWhiteSpace(configKey) && config.ConfigKey == configKey) { servicePath = config.ConfigValue; } } if (string.IsNullOrWhiteSpace(address)) { throw new Exception($"δÕÒµ½ÅäÖõØÖ·£º{category} - BASE"); } string normalizedPath = string.IsNullOrWhiteSpace(servicePath) ? string.Empty : (servicePath.StartsWith("/") ? servicePath : $"/{servicePath}"); string serviceAddress = $"{address}{normalizedPath}"; if (method == HttpMethod.Get) { return await GetAsync(serviceAddress, timeOut, configDict); } if (method == HttpMethod.Post) { return await PostAsync(serviceAddress, requestContent, contentType, timeOut, configDict); } if (method == HttpMethod.Put) { return await PutAsync(serviceAddress, requestContent, contentType, timeOut, configDict); } if (method == HttpMethod.Delete) { return await DeleteAsync(serviceAddress, timeOut, configDict); } throw new NotSupportedException($"²»Ö§³ÖµÄÇëÇó·½·¨£º{method}"); } /// /// °´ÅäÖ÷ÖÀà·¢ËÍGETÇëÇó /// public static async Task HTTPGetAsync(string category, string? requestContent, string? configKey, int timeOut = 60) { if (string.IsNullOrWhiteSpace(category) || string.IsNullOrWhiteSpace(requestContent) || string.IsNullOrWhiteSpace(configKey)) { throw new ArgumentException("´«ÈëÅäÖò»ÄÜΪ¿Õ", nameof(category)); } WebResponseContent content = new WebResponseContent(); string result = await SendAsync(requestContent, HttpMethod.Get, category, configKey, "application/json", timeOut); return content = JsonSerializer.Deserialize(result) ?? new WebResponseContent { Status = false, Message = "½âÎöÏìӦʧ°Ü" }; } /// /// °´ÅäÖ÷ÖÀà·¢ËÍPOSTÇëÇó /// public static async Task HTTPPostAsync(string category, string? requestContent, string? configKey, int timeOut = 60) { if (string.IsNullOrWhiteSpace(category) || string.IsNullOrWhiteSpace(requestContent) || string.IsNullOrWhiteSpace(configKey)) { throw new ArgumentException("´«ÈëÅäÖò»ÄÜΪ¿Õ", nameof(category)); } WebResponseContent content = new WebResponseContent(); string result = await SendAsync(requestContent, HttpMethod.Post, category, configKey, "application/json", timeOut); return content = JsonSerializer.Deserialize(result) ?? new WebResponseContent { Status = false, Message = "½âÎöÏìӦʧ°Ü" }; } } }