dengjunjie
5 天以前 4f39dcc195f28fa275fc2d065fbf1bf6a46c21b7
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
 
using Newtonsoft.Json;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using WIDESEA_Common.Log;
 
namespace WIDESEA_Comm.Http
{
    public class HttpHelpers
    {
        private const int Timeout = 20 * 1000;
 
        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parm">参数</param>
        /// <param name="rquestName">接口名称,用于日志分类</param>
        /// <returns></returns>
        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("API", rquestName, "请求异常", new { 请求报文 = parm, 接收报文 = responseContent, 错误 = ex.Message });
                throw ex;
            }
        }
        public static async Task<string?> PostAsync(string serviceAddress, string requestJson = null, 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 (KeyValuePair<string, string> header in headers)
                        {
                            httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                        }
                    }
 
                    result = await httpClient.PostAsync(serviceAddress, httpContent).Result.Content.ReadAsStringAsync();
                }
 
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
            }
        }
        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parm">参数</param>
        /// <param name="rquestName">接口名称,用于日志分类</param>
        /// <returns></returns>
        public static T Post<T>(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<T>(responseContent);
            }
            catch (Exception ex)
            {
                WriteLog.Write_Log("API", rquestName, "请求异常", new { 请求报文 = parm, 接收报文 = responseContent, 错误 = ex.Message });
                throw ex;
            }
        }
 
 
        /// <summary>
        /// get请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="parm">请求参数,添加在url</param>
        /// <param name="rquestName"></param>
        /// <returns></returns>
        public static T Get<T>(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<Dictionary<string, string>>(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("API", rquestName, "请求成功", new { 请求报文 = parm, 接收报文 = responseContent });
                return JsonConvert.DeserializeObject<T>(responseContent);
            }
            catch (Exception ex)
            {
                WriteLog.Write_Log("API", rquestName, "请求异常", new { 请求报文 = parm, 接收报文 = responseContent, 错误 = ex.Message });
                throw ex;
            }
        }
 
    }
}