1
HuBingJie
2025-11-13 d58196721475e968769d708d9c14f60dd8d5671f
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core.LogHelper;
 
namespace WIDESEA_Core.Helper
{
    public class HttpHelper
    {
        public static async Task<string> GetAsync(string serviceAddress, Dictionary<string, string>? headers = null)
        {
            string result = string.Empty;
            DateTime beginDate = DateTime.Now;
            try
            {
                using HttpClient httpClient = new HttpClient();
                httpClient.Timeout = new TimeSpan(0, 0, 60);
                
                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)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                Logger.Add(serviceAddress, "", result, beginDate);
            }
        }
 
        public static async Task<string?> PostAsync(string serviceAddress, string requestJson = "", string contentType = "application/json", Dictionary<string, string>? headers = null)
        {
            string result = string.Empty;
            DateTime beginDate = DateTime.Now;
            try
            {
                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);
 
                    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)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                Logger.Add(serviceAddress, requestJson, result, beginDate);
            }
        }
 
        public static string Get(string serviceAddress, string contentType = "application/json", Dictionary<string, string>? headers = null)
        {
            string result = string.Empty;
            DateTime beginDate = DateTime.Now;
            try
            {
                using HttpClient httpClient = new HttpClient();
                httpClient.Timeout = new TimeSpan(0, 0, 60);
 
                if (headers != null)
                {
                    foreach (var header in headers)
                        httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
 
                result = httpClient.GetStringAsync(serviceAddress).Result;
                return result;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                Logger.Add(serviceAddress, "", result, beginDate);
            }
        }
 
        public static string Post(string serviceAddress, string requestJson = "", string contentType = "application/json", Dictionary<string, string>? headers = null)
        {
            string result = string.Empty;
            DateTime beginDate = DateTime.Now;
            try
            {
                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);
 
                    if (headers != null)
                    {
                        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)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                Logger.Add(serviceAddress, requestJson, result, beginDate);
            }
        }
 
        /// <summary>
        /// POST请求(异步版本)- 解决405问题
        /// </summary>
        /// <param name="serviceAddress">服务地址</param>
        /// <param name="requestJson">请求JSON</param>
        /// <param name="contentType">内容类型</param>
        /// <param name="headers">请求头</param>
        /// <returns>响应结果</returns>
        /// <summary>
        /// POST请求(同步版本,兼容原有代码)
        /// </summary>
        // 如果上面的方法还有问题,使用这个简化版本
        public static string PostSync(string serviceAddress, string requestJson = "", string contentType = "application/json", Dictionary<string, string>? headers = null)
        {
            string result = string.Empty;
            DateTime beginDate = DateTime.Now;
            try
            {
                using (var httpContent = new StringContent(requestJson, Encoding.UTF8, contentType))
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(600);
 
                    // 设置默认请求头 - 使用简单的 User-Agent
                    httpClient.DefaultRequestHeaders.Add("Accept", "*/*");
                    httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
                    httpClient.DefaultRequestHeaders.Add("Connection", "keep-alive");
                    httpClient.DefaultRequestHeaders.Add("User-Agent", "WMS-Client/1.0"); // 简单的 User-Agent
 
                    if (headers != null)
                    {
                        foreach (var header in headers)
                            httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
 
                    var response = httpClient.PostAsync(serviceAddress, httpContent).Result;
 
                    Console.WriteLine($"HTTP状态码: {(int)response.StatusCode} - {response.StatusCode}");
 
                    if (!response.IsSuccessStatusCode)
                    {
                        throw new HttpRequestException($"HTTP请求失败: {(int)response.StatusCode} - {response.StatusCode}");
                    }
 
                    result = response.Content.ReadAsStringAsync().Result;
                    return result;
                }
            }
            catch (Exception e)
            {
                throw new Exception($"POST请求失败: {e.Message}");
            }
            finally
            {
                Logger.Add(serviceAddress, requestJson, result, beginDate);
            }
        }
 
 
        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="serviceAddress">服务地址</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="headers">请求头</param>
        /// <returns>响应结果</returns>
        public static string GetRequest(string serviceAddress, Dictionary<string, string>? parameters = null, Dictionary<string, string>? headers = null)
        {
            string result = string.Empty;
            DateTime beginDate = DateTime.Now;
            try
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(60);
 
                    // 设置请求头
                    httpClient.DefaultRequestHeaders.Add("Accept", "*/*");
                    httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
                    httpClient.DefaultRequestHeaders.Add("Connection", "keep-alive");
                    httpClient.DefaultRequestHeaders.Add("User-Agent", "WMS-Client/1.0");
 
                    if (headers != null)
                    {
                        foreach (var header in headers)
                            httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
 
                    // 构建带参数的 URL
                    string url = serviceAddress;
                    if (parameters != null && parameters.Count > 0)
                    {
                        var queryParams = string.Join("&", parameters.Select(p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value)}"));
                        url += (url.Contains("?") ? "&" : "?") + queryParams;
                    }
 
                    var response = httpClient.GetAsync(url).Result;
 
                    Console.WriteLine($"GET 状态码: {(int)response.StatusCode} - {response.StatusCode}");
 
                    if (!response.IsSuccessStatusCode)
                    {
                        throw new HttpRequestException($"GET 请求失败: {(int)response.StatusCode} - {response.StatusCode}");
                    }
 
                    result = response.Content.ReadAsStringAsync().Result;
                    return result;
                }
            }
            catch (Exception e)
            {
                throw new Exception($"GET 请求失败: {e.Message}");
            }
            finally
            {
                Logger.Add(serviceAddress, parameters != null ? JsonConvert.SerializeObject(parameters) : "No Parameters", result, beginDate);
            }
        }
    }
}