using Newtonsoft.Json; using System.Net; using System.Net.Http.Headers; using System.Text; using WIDESEA_Common.Log; namespace WIDESEA_Comm.Http { public class HttpHelper { private const int Timeout = 10 * 1000; public static async Task GetAsync(string serviceAddress, Dictionary parameters, string contentType = "application/json", Dictionary? headers = null) { try { string result = string.Empty; using HttpClient httpClient = new HttpClient(); httpClient.Timeout = new TimeSpan(0, 0, 60); // 将参数拼接到URL中 string queryString = string.Join("&", parameters.Select(x => $"{x.Key}={x.Value}")); serviceAddress += "?" + queryString; if (headers != null) { foreach (var header in headers) httpClient.DefaultRequestHeaders.Add(header.Key, header.Value); } result = await httpClient.GetAsync(serviceAddress).Result.Content.ReadAsStringAsync(); return result; } catch (Exception e) { Console.WriteLine(e.Message); } return null; } // 用于追踪每个请求的调用次数和最后请求时间。 private static readonly Dictionary requestTracker = new(); public static async Task PostAsync(string serviceAddress, string requestJson = null, string contentType = "application/json", Dictionary? headers = null) { try { if (serviceAddress.Contains("http://c24-cellmi3:12020")) { // 将 JSON 字符串转换为字典 var parameters = JsonConvert.DeserializeObject>(requestJson); // 创建一个新的字典,排除 RequestTime 和 SessionId var filteredParameters = parameters.Where(p => p.Key != "RequestTime" && p.Key != "SessionId").ToDictionary(p => p.Key, p => p.Value); string requestKey = $"{serviceAddress}:{JsonConvert.SerializeObject(filteredParameters)}"; // 检查请求次数和时间限制 if (requestTracker.TryGetValue(requestKey, out var requestInfo)) { if (requestInfo.Count >= 5 && DateTime.Now < requestInfo.LastRequestTime.AddMinutes(3)) { // 如果请求次数超过限制且未超过10分钟,抛出异常 throw new InvalidOperationException("请求次数已达到限制,请稍后再试。"); } } // 更新请求跟踪信息 if (requestTracker.ContainsKey(requestKey)) { requestTracker[requestKey] = (requestInfo.Count + 1, DateTime.Now); } else { requestTracker[requestKey] = (1, DateTime.Now); } } string result = string.Empty; using (HttpContent httpContent = new StringContent(requestJson)) { httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); using HttpClient httpClient = new HttpClient(); httpClient.Timeout = new TimeSpan(0, 0, 120); if (headers != null) { foreach (var header in headers) httpClient.DefaultRequestHeaders.Add(header.Key, header.Value); } result = await httpClient.PostAsync(serviceAddress, httpContent).Result.Content.ReadAsStringAsync(); } return result; } catch (Exception e) { Console.WriteLine(e.Message); } return null; } public static string Get(string serviceAddress, string contentType = "application/json", Dictionary? headers = null) { try { string result = string.Empty; using HttpClient httpClient = new HttpClient(); httpClient.Timeout = new TimeSpan(0, 0, 60); foreach (var header in headers) httpClient.DefaultRequestHeaders.Add(header.Key, header.Value); result = httpClient.GetStringAsync(serviceAddress).Result; return result; } catch (Exception e) { Console.WriteLine(e.Message); } return null; } public static string Post(string serviceAddress, string requestJson = null, string contentType = "application/json", Dictionary? headers = null) { try { string result = string.Empty; using (HttpContent httpContent = new StringContent(requestJson)) { httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); using HttpClient httpClient = new HttpClient(); httpClient.Timeout = new TimeSpan(0, 0, 60); foreach (var header in headers) httpClient.DefaultRequestHeaders.Add(header.Key, header.Value); result = httpClient.PostAsync(serviceAddress, httpContent).Result.Content.ReadAsStringAsync().Result; } return result; } catch (Exception e) { Console.WriteLine(e.Message); } return null; } /// /// post请求 /// /// /// 参数 /// 接口名称,用于日志分类 /// public static string Post(string url, object parm, string rquestName = "") { HttpWebResponse response = null; StreamReader resultReader = null; string responseContent = string.Empty; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = Timeout; request.Method = "POST"; request.ContentType = "application/json; charset=UTF-8"; parm = parm ?? ""; byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(parm)); request.ContentLength = data.Length; using (Stream newStream = request.GetRequestStream()) { newStream.Write(data, 0, data.Length); }; response = (HttpWebResponse)request.GetResponse(); Stream webStream = response.GetResponseStream(); if (webStream == null) { throw new Exception("Network error"); } int statsCode = (int)response.StatusCode; resultReader = new StreamReader(webStream, Encoding.UTF8); responseContent = resultReader.ReadToEnd(); if (response != null) response.Close(); if (resultReader != null) resultReader.Close(); if (statsCode != 200) { throw new Exception("异常,响应码:" + statsCode.ToString()); } //WriteLog.Write_Log("System/API请求", rquestName, "请求成功", new { 请求报文 = parm, 接收报文 = responseContent }); return responseContent; } catch (Exception ex) { WriteLog.Write_Log("System/API请求", rquestName, "请求异常", new { 请求报文 = parm, 接收报文 = responseContent, 错误 = ex.Message }); throw ex; } } /// /// post请求 /// /// /// 参数 /// 接口名称,用于日志分类 /// public static T Post(string url, object parm, string rquestName = "") where T : class { HttpWebResponse response = null; StreamReader resultReader = null; string responseContent = string.Empty; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = Timeout; request.Method = "POST"; request.ContentType = "application/json; charset=UTF-8"; parm = parm ?? ""; byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(parm)); request.ContentLength = data.Length; using (Stream newStream = request.GetRequestStream()) { newStream.Write(data, 0, data.Length); }; response = (HttpWebResponse)request.GetResponse(); Stream webStream = response.GetResponseStream(); if (webStream == null) { throw new Exception("Network error"); } int statsCode = (int)response.StatusCode; resultReader = new StreamReader(webStream, Encoding.UTF8); responseContent = resultReader.ReadToEnd(); if (response != null) response.Close(); if (resultReader != null) resultReader.Close(); if (statsCode != 200) { throw new Exception("异常,响应码:" + statsCode.ToString()); } //WriteLog.Write_Log("System/API请求", rquestName, "请求成功", new { 请求报文 = parm, 接收报文 = responseContent }); return JsonConvert.DeserializeObject(responseContent); } catch (Exception ex) { WriteLog.Write_Log("System/API请求", rquestName, "请求异常", new { 请求报文 = parm, 接收报文 = responseContent, 错误 = ex.Message }); throw ex; } } /// /// get请求 /// /// /// /// 请求参数,添加在url /// /// public static T Get(string url, object parm = null, string rquestName = "") where T : class { HttpWebResponse response = null; StreamReader resultReader = null; string responseContent = string.Empty; try { if (parm != null) { var datas = JsonConvert.DeserializeObject>(JsonConvert.SerializeObject(parm)); var keyList = datas.Keys; int index = 0; foreach (var key in datas.Keys) { if (index == 0) { url += $"?{key}={datas[key]}"; } else { url += $"&{key}={datas[key]}"; } index++; } } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = Timeout; request.Method = "GET"; request.ContentType = "application/json; charset=UTF-8"; response = (HttpWebResponse)request.GetResponse(); Stream webStream = response.GetResponseStream(); if (webStream == null) { throw new Exception("Network error"); } int statsCode = (int)response.StatusCode; resultReader = new StreamReader(webStream, Encoding.UTF8); responseContent = resultReader.ReadToEnd(); if (response != null) response.Close(); if (resultReader != null) resultReader.Close(); if (statsCode != 200) { throw new Exception("异常,响应码:" + statsCode.ToString()); } WriteLog.Write_Log("System/API请求", rquestName, "请求成功", new { 请求报文 = parm, 接收报文 = responseContent }); return JsonConvert.DeserializeObject(responseContent); } catch (Exception ex) { WriteLog.Write_Log("System/API请求", rquestName, "请求异常", new { 请求报文 = parm, 接收报文 = responseContent, 错误 = ex.Message }); throw ex; } } } }