huangxiaoqiang
昨天 2d9272bdcdbdbca81396a61493e4ef6a822dcf4a
ÏîÄ¿´úÂë/WCS/WIDESEAWCS_Server/WIDESEAWCS_Common/Http/HttpHelper.cs
@@ -1,5 +1,6 @@
using Newtonsoft.Json;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using WIDESEA_Common.Log;
@@ -9,6 +10,141 @@
    {
        private const int Timeout = 10 * 1000;
        public static async Task<string> GetAsync(string serviceAddress, Dictionary<string, object> parameters, string contentType = "application/json", Dictionary<string, string>? 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<string, (int Count, DateTime LastRequestTime)> requestTracker = new();
        public static async Task<string> PostAsync(string serviceAddress, string requestJson = null, string contentType = "application/json", Dictionary<string, string>? headers = null)
        {
            try
            {
                if (serviceAddress.Contains("http://c24-cellmi3:12020"))
                {
                    // å°† JSON å­—符串转换为字典
                    var parameters = JsonConvert.DeserializeObject<Dictionary<string, object>>(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<string, string>? 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<string, string>? 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;
        }
        /// <summary>
        /// post请求
        /// </summary>