qinchulong
2025-03-29 039a4a5433e7f80adc88b491b549e5d9486e4f9a
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading;
 
namespace WIDESEA_Core.Utilities
{
    public enum RequestMethod
    {
        Get = 1,//获取
        Post = 2,//投寄
        OPTIONS = 3,//选项
        HEAD = 4,//头
        PUT = 5,//放置
        DELETE = 6,//删除
        TRACE = 7,//跟踪
        CONNECT = 8,//连接
    }
    public class WebApiHelper
    {
 
        //internal static string MesBlankDownAddress = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["MesBlankDown"]);
 
        //application/x-www-form-urlencoded//application/json
        /// <summary>
        /// webapi地址调用函数
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="user_Id">验证用户</param>
        /// <param name="reqMethod">请求方式</param>
        /// <param name="param">参数(json)</param>
        /// <returns></returns>
        public static JObject SendInfoToWebAPI(string url, string user_Id = null, string reqMethod = "Get", JArray param = null)
        {
            //JArray jsonobj =new JArray();
            JObject jobj = null;
            HttpWebRequest webRequest = null;
            HttpWebResponse webResponse = null;
            try
            {
                Thread.Sleep(3500);
                webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                //webRequest.ContentType = "application/x-www-form-urlencoded";
                //webRequest.ContentType = "application/json";
                string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
                webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                //webRequest.UserAgent = "Mozilla/4.0   (compatible;   MSIE   6.0;   Windows   NT   5.1;   SV1;   .NET   CLR  2.0.50727) ";
                webRequest.Method = reqMethod;
                webRequest.AllowAutoRedirect = false;
                webRequest.Timeout = 50000;
                byte[] PostData = null;
                if (user_Id != null)
                    webRequest.Headers.Add("Authorization", user_Id);
                //webRequest.Headers.Add("Authorization", "A1203016");
                if (param != null)
                {
                    //string paraUrlCoded = System.Web.HttpUtility.UrlEncode("paramaters");
                    //paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(jsonParas);
                    PostData = Encoding.UTF8.GetBytes(param[0].ToString());
                    webRequest.ContentLength = PostData.Length;
                }
                if (reqMethod == RequestMethod.Post.ToString())
                {
                    Stream RequestStream = webRequest.GetRequestStream();
                    if (PostData != null)
                    {
                        RequestStream.Write(PostData, 0, PostData.Length);
                    }
                    RequestStream.Close();
                    RequestStream.Dispose();
                }
                webResponse = (HttpWebResponse)webRequest.GetResponse();
                Stream ResponseStrem = webResponse.GetResponseStream();
                StreamReader reader = new StreamReader(ResponseStrem);
                string ValueString = reader.ReadToEnd();
                jobj = JObject.Parse(ValueString);
                //jsonobj = JArray.Parse(ValueString);
                ResponseStrem.Dispose();
                webResponse.Close();
            }
            catch (ThreadInterruptedException threx)
            {
                string messge = string.Format("调用接口超时,线程被中断,Url=[{0}]", url);
                //LogMessageHelper.RecordLogMessage(messge, threx);
                //Log4netHelper.Logger_Error.Error(messge);
            }
            catch (WebException webex)
            {
                //webResponse = (HttpWebResponse)webex.Response;
                //StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                //string temp = sr.ReadToEnd();
                string messge = string.Format("通信接口错误,Url={0}", url);
                //LogMessageHelper.RecordLogMessage(messge, webex);
            }
            catch (Exception ex)
            {
                string messge = string.Format("通信接口错误,Url={0}", url);
                //LogMessageHelper.RecordLogMessage(messge, ex);
            }
            finally
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                    webResponse = null;
                }
                if (webRequest != null)
                {
                    webRequest.Abort();
                    webRequest = null;
                }
            }
            return jobj;
        }
 
        internal static JObject SendAsyncInfoToWebAPI(string url, string user_Id = null, string reqMethod = "Get", JArray param = null)
        {
            //JArray jsonobj =new JArray();
            JObject jobj = null;
            HttpWebRequest webRequest = null;
            HttpWebResponse webResponse = null;
            try
            {
                webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.Method = reqMethod;
                webRequest.AllowAutoRedirect = false;
                webRequest.Timeout = 5000;
                byte[] PostData = null;
                if (user_Id != null)
                    webRequest.Headers.Add("Authorization", user_Id);
                //webRequest.Headers.Add("Authorization", "A1203016");
                if (param != null)
                {
                    //string paraUrlCoded = System.Web.HttpUtility.UrlEncode("paramaters");
                    //paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(jsonParas);
                    PostData = Encoding.UTF8.GetBytes(param[0].ToString());
                    webRequest.ContentLength = PostData.Length;
                }
                if (reqMethod == RequestMethod.Post.ToString())
                {
                    Stream RequestStream = webRequest.GetRequestStream();
                    if (PostData != null)
                    {
                        RequestStream.Write(PostData, 0, PostData.Length);
                    }
                    RequestStream.Close();
                    RequestStream.Dispose();
                }
                //webResponse = (HttpWebResponse)webRequest.GetResponse();
                webRequest.BeginGetResponse(AsyncCallbackResponse, webRequest);
 
 
                //Stream ResponseStrem = webResponse.GetResponseStream();
                //StreamReader reader = new StreamReader(ResponseStrem);
                //string ValueString = reader.ReadToEnd();
                //jobj = JObject.Parse(ValueString);
                //jsonobj = JArray.Parse(ValueString);
                //ResponseStrem.Dispose();
                webResponse.Close();
            }
            catch (WebException webex)
            {
                webResponse = (HttpWebResponse)webex.Response;
                StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                string temp = sr.ReadToEnd();
                string messge = string.Format("通信接口错误,Url={0}", url);
            }
            catch (Exception ex)
            {
                string messge = string.Format("通信接口错误,Url={0}", url);
            }
            finally
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                    webResponse = null;
                }
                if (webRequest != null)
                {
                    webRequest.Abort();
                    webRequest = null;
                }
            }
            return jobj;
        }
 
        internal static JArray SendInfoToWebAPIList(string url, string user_Id = null, string reqMethod = "Get", JArray param = null)
        {
            JArray jsonobj = new JArray();
            //JObject jobj = null;
            HttpWebRequest webRequest = null;
            HttpWebResponse webResponse = null;
            try
            {
                webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                //webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.ContentType = "application/json";
                //webRequest.UserAgent = "Mozilla/4.0   (compatible;   MSIE   6.0;   Windows   NT   5.1;   SV1;   .NET   CLR  2.0.50727) ";
                webRequest.Method = reqMethod;
                webRequest.AllowAutoRedirect = false;
                webRequest.Timeout = 50000;
                byte[] PostData = null;
                if (user_Id != null)
                    webRequest.Headers.Add("Authorization", user_Id);
                //webRequest.Headers.Add("Authorization", "A1203016");
                if (param != null)
                {
                    //string paraUrlCoded = System.Web.HttpUtility.UrlEncode("paramaters");
                    //paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(jsonParas);
                    PostData = Encoding.UTF8.GetBytes(param[0].ToString());
                    webRequest.ContentLength = PostData.Length;
                }
                if (reqMethod == RequestMethod.Post.ToString())
                {
                    Stream RequestStream = webRequest.GetRequestStream();
                    if (PostData != null)
                    {
                        RequestStream.Write(PostData, 0, PostData.Length);
                    }
                    RequestStream.Close();
                    RequestStream.Dispose();
                }
                webResponse = (HttpWebResponse)webRequest.GetResponse();
                Stream ResponseStrem = webResponse.GetResponseStream();
                StreamReader reader = new StreamReader(ResponseStrem);
                string ValueString = reader.ReadToEnd();
                //jobj = JObject.Parse(ValueString);
                jsonobj = JArray.Parse(ValueString);
                ResponseStrem.Dispose();
                webResponse.Close();
            }
            catch (WebException webex)
            {
                //webResponse = (HttpWebResponse)webex.Response;
                //StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                //string temp = sr.ReadToEnd();
                string messge = string.Format("通信接口错误,Url={0}", url);
            }
            catch (Exception ex)
            {
                string messge = string.Format("通信接口错误,Url={0}", url);
            }
            finally
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                    webResponse = null;
                }
                if (webRequest != null)
                {
                    webRequest.Abort();
                    webRequest = null;
                }
            }
            return jsonobj;
        }
 
        private static void AsyncCallbackResponse(IAsyncResult ar)
        {
            HttpWebRequest webrequest = ar.AsyncState as HttpWebRequest;
            var webresponse = webrequest.EndGetResponse(ar) as HttpWebResponse;
            Stream ResponseStrem = webresponse.GetResponseStream();
            using (StreamReader reader = new StreamReader(ResponseStrem))
            {
                string ValueString = reader.ReadToEnd();
            }
        }
 
        /// <summary>  
        /// 生成Json格式  
        /// </summary>  
        public static string GetJson(object obj)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, obj);
                string szJson = Encoding.UTF8.GetString(stream.ToArray());
                return szJson;
            }
        }
 
        /// <summary>  
        /// 生成Json格式  
        /// </summary>  
        public static string GetJson_2<T>(T t)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, t);
                string szJson = Encoding.UTF8.GetString(stream.ToArray());
                return szJson;
            }
        }
        /// <summary>  
        /// Json转Model  
        /// </summary>  
        public static T ParseFromJson<T>(string szJson)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }
        /// <summary>  
        /// Json转List
        /// </summary>  
        public static List<T> ParseToListFromJson<T>(JArray ja)
        {
            var result = new List<T>();
            foreach (var item in ja)
            {
                result.Add(ParseFromJson<T>(item.ToString()));
            }
            return result;
        }
    }
}