wanshenmean
2026-03-09 1181f9f764b14abd6e9f598f89f8507b4bbfad0d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
using SqlSugar;
using System.Text;
using System.Text.Json;
using WIDESEAWCS_Code;
using WIDESEAWCS_Core.Helper;
 
namespace WIDESEAWCS_Core.Http
{
    public static class HttpRequestHelper
    {
        /// <summary>
        /// Òì²½·¢ËÍHTTPÇëÇó²¢·µ»ØÏìÓ¦ÄÚÈÝ
        /// </summary>
        /// <param name="serviceAddress">ÇëÇóµØÖ·</param>
        /// <param name="method">ÇëÇó·½·¨</param>
        /// <param name="requestContent">ÇëÇóÄÚÈÝ</param>
        /// <param name="contentType">ÄÚÈÝÀàÐÍ</param>
        /// <param name="timeOut">³¬Ê±Ê±¼ä£¨Ã룩</param>
        /// <param name="headers">ÇëÇóÍ·</param>
        /// <returns>ÏìÓ¦ÄÚÈÝ</returns>
        public static async Task<string> SendAsync(string serviceAddress, HttpMethod method, string? requestContent = null, string contentType = "application/json", int timeOut = 60, Dictionary<string, string>? 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;
        }
 
        /// <summary>
        /// Òì²½·¢ËÍHTTP GETÇëÇó²¢·µ»ØÏìÓ¦ÄÚÈÝ
        /// </summary>
        public static Task<string> GetAsync(string serviceAddress, int timeOut = 60, Dictionary<string, string>? headers = null)
        {
            return SendAsync(serviceAddress, HttpMethod.Get, null, "application/json", timeOut, headers);
        }
 
        /// <summary>
        /// Òì²½·¢ËÍHTTP POSTÇëÇó²¢·µ»ØÏìÓ¦ÄÚÈÝ
        /// </summary>
        public static Task<string> PostAsync(string serviceAddress, string? requestJson = null, string contentType = "application/json", int timeOut = 60, Dictionary<string, string>? headers = null)
        {
            return SendAsync(serviceAddress, HttpMethod.Post, requestJson, contentType, timeOut, headers);
        }
 
        /// <summary>
        /// Òì²½·¢ËÍHTTP PUTÇëÇó²¢·µ»ØÏìÓ¦ÄÚÈÝ
        /// </summary>
        public static Task<string> PutAsync(string serviceAddress, string? requestJson = null, string contentType = "application/json", int timeOut = 60, Dictionary<string, string>? headers = null)
        {
            return SendAsync(serviceAddress, HttpMethod.Put, requestJson, contentType, timeOut, headers);
        }
 
        /// <summary>
        /// Òì²½·¢ËÍHTTP DELETEÇëÇó²¢·µ»ØÏìÓ¦ÄÚÈÝ
        /// </summary>
        public static Task<string> DeleteAsync(string serviceAddress, int timeOut = 60, Dictionary<string, string>? headers = null)
        {
            return SendAsync(serviceAddress, HttpMethod.Delete, null, "application/json", timeOut, headers);
        }
 
        /// <summary>
        /// ¸ù¾ÝÊý¾Ý¿âÅäÖ÷¢ËÍHTTPÇëÇó²¢·µ»ØÏìÓ¦ÄÚÈÝ
        /// </summary>
        /// <param name="requestContent">ÇëÇóÄÚÈÝ</param>
        /// <param name="method">ÇëÇó·½·¨</param>
        /// <param name="category">ÅäÖ÷ÖÀà</param>
        /// <param name="categoryItem">ÅäÖÃÏî</param>
        /// <param name="contentType">ÄÚÈÝÀàÐÍ</param>
        /// <param name="timeOut">³¬Ê±Ê±¼ä£¨Ã룩</param>
        /// <returns>ÏìÓ¦ÄÚÈÝ</returns>
        public static async Task<string> SendAsync(string? requestContent, HttpMethod method, string? category, string? configKey, string contentType = "application/json", int timeOut = 60)
        {
            ISqlSugarClient? db = App.GetService<ISqlSugarClient>();
            if (db == null)
            {
                throw new InvalidOperationException("Êý¾Ý¿â·þÎñδ³õʼ»¯");
            }
 
            var configs = await db.Ado.SqlQueryAsync<Sys_Config>(
                "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<string, string> configDict = new Dictionary<string, string>();
 
            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}");
        }
 
        /// <summary>
        /// °´ÅäÖ÷ÖÀà·¢ËÍGETÇëÇó
        /// </summary>
        public static async Task<WebResponseContent> 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<WebResponseContent>(result) ?? new WebResponseContent { Status = false, Message = "½âÎöÏìӦʧ°Ü" };
        }
 
        /// <summary>
        /// °´ÅäÖ÷ÖÀà·¢ËÍPOSTÇëÇó
        /// </summary>
        public static async Task<WebResponseContent> 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<WebResponseContent>(result) ?? new WebResponseContent { Status = false, Message = "½âÎöÏìӦʧ°Ü" };
        }
    }
}