chr
2024-08-21 9ee7d3bd9c58a204b1efe38e6be61155bbb15c16
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
 
namespace PdmAlert.Util
{
    [Serializable]
    public class Result<T>
    {
        [JsonProperty("success")]
        public bool success
        {
            get; set;
        }
 
        [JsonProperty("message")]
        public string message
        {
            get; set;
        }
 
        [JsonProperty("code")]
        public int code
        {
            get; set;
        }
 
        [JsonProperty("result")]
        public T result
        {
            get; set;
        }
    }
 
    public static class ResultHandler
    {
        public static T HandleResult<T>(this Result<T> result)
        {
            if (result.success)
            {
                return result.result;
            }
            throw new CustomWebException(result.message);
        }
    }
 
    /// <summary>
    /// 自定义从Web返回的异常
    /// </summary>
    public class CustomWebException : Exception
    {
        public CustomWebException()
        {
 
        }
 
        public CustomWebException(string message) : base(message)
        {
 
        }
 
        public CustomWebException(string message, Exception inner) : base(message, inner)
        {
 
        }
    }
 
    public class JsonUtil
    {
        static readonly JsonSerializerSettings JsSetting = new JsonSerializerSettings()
        {
            NullValueHandling = NullValueHandling.Ignore
        };
 
        public static T Deserialize<T>(string jsonStr)
        {
            return JsonConvert.DeserializeObject<T>(jsonStr);
        }
 
        public static string Serialize(object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }
 
        public static string Stringfiy(object obj)
        {
            return JsonConvert.SerializeObject(obj, Formatting.Indented, JsSetting);
        }
 
    }
 
    public static class HttpUtil
    {
 
        /// <summary>
        /// Http GET 同步获取对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="client">客户端</param>
        /// <param name="url">url</param>
        /// <param name="models">参数</param>
        /// <returns>Http返回结果</returns>
        public static Result<T> GetSyncAction<T>(this HttpClient client, string url, params object[] models)
        {
            return JsonUtil.Deserialize<Result<T>>(GetSyncAction(client, url, models));
        }
 
        /// <summary>
        /// Http GET 同步获取字符
        /// </summary>
        /// <param name="client">客户端</param>
        /// <param name="url">url</param>
        /// <param name="models">参数</param>
        /// <returns>Http返回结果</returns>
        public static string GetSyncAction(this HttpClient client, string url, params object[] models)
        {
            try
            {
                foreach (object model in models)
                {
                    url = url.ModelToUriParam(model);
                }
 
                Task<string> task = client.GetStringAsync(url);
                task.Wait();
                return task.Result;
            }
            catch (Exception e)
            {
                throw new CustomWebException("请求异常", e);
            }
        }
 
        /// <summary>
        /// Http GET 异步获取对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="client">客户端</param>
        /// <param name="url">url</param>
        /// <param name="models">参数</param>
        /// <returns>异步Http返回结果</returns>
        public static async Task<Result<T>> GetAsyncAction<T>(this HttpClient client, string url, params object[] models)
        {
            try
            {
                foreach (object model in models)
                {
                    url = url.ModelToUriParam(model);
                }
                return JsonUtil.Deserialize<Result<T>>(await client.GetStringAsync(url));
            }
            catch (Exception e)
            {
                throw new CustomWebException("请求异常", e);
            }
        }
 
        /// <summary>
        /// Http POST 同步获取对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="client">客户端</param>
        /// <param name="url">url</param>
        /// <param name="data">参数json字符</param>
        /// <returns>Http返回结果</returns>
        public static Result<T> PostSyncAction<T>(this HttpClient client, string url, string data)
        {
            StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
            Task<HttpResponseMessage> task = client.PostAsync(url, content);
            task.Wait();
            HttpResponseMessage response = task.Result;
            response.EnsureSuccessStatusCode();
            Task<string> task2 = response.Content.ReadAsStringAsync();
            task2.Wait();
            string responseBody = task2.Result;
            return JsonUtil.Deserialize<Result<T>>(responseBody);
        }
 
        /// <summary>
        /// Http POST 同步获取对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="client">客户端</param>
        /// <param name="url">url</param>
        /// <param name="content">Http负载</param>
        /// <returns>Http返回结果</returns>
        public static Result<T> PostSyncAction<T>(this HttpClient client, string url, HttpContent content)
        {
            Task<HttpResponseMessage> task = client.PostAsync(url, content);
            task.Wait();
            HttpResponseMessage response = task.Result;
            response.EnsureSuccessStatusCode();
            Task<string> task2 = response.Content.ReadAsStringAsync();
            task2.Wait();
            return JsonUtil.Deserialize<Result<T>>(task2.Result);
        }
 
        /// <summary>
        /// Http POST 同步获取对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="client">客户端</param>
        /// <param name="data">参数对象</param>
        /// <param name="url">url</param>
        /// <returns>Http返回结果</returns>
        public static Result<T> PostSyncAction<T>(this HttpClient client, object data, string url)
        {
            string dataStr = JsonUtil.Serialize(data);
            StringContent content = new StringContent(dataStr, Encoding.UTF8, "application/json");
            Task<HttpResponseMessage> task = client.PostAsync(url, content);
            task.Wait();
            HttpResponseMessage response = task.Result;
            response.EnsureSuccessStatusCode();
            Task<string> task2 = response.Content.ReadAsStringAsync();
            task2.Wait();
            string responseBody = task2.Result;
            return JsonUtil.Deserialize<Result<T>>(responseBody);
        }
 
        public static string PostSyncAction(this HttpClient client, string url, string data)
        {
            StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
            Task<HttpResponseMessage> task = client.PostAsync(url, content);
            task.Wait();
            HttpResponseMessage response = task.Result;
            response.EnsureSuccessStatusCode();
            Task<string> task2 = response.Content.ReadAsStringAsync();
            task2.Wait();
            return task2.Result;
        }
 
        public static async Task<T> PostAsyncAction<T>(this HttpClient client, string url, string data)
        {
            StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync(url, content);
            _ = response.EnsureSuccessStatusCode();
            return JsonUtil.Deserialize<T>(await response.Content.ReadAsStringAsync());
        }
 
        public static async Task<Result<T>> PostAsyncAction<T>(this HttpClient client, string url, object data)
        {
            string dataStr = JsonUtil.Serialize(data);
            StringContent content = new StringContent(dataStr, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync(url, content);
            _ = response.EnsureSuccessStatusCode();
            return JsonUtil.Deserialize<Result<T>>(await response.Content.ReadAsStringAsync());
        }
 
        public static async Task<Result<T>> PostAsyncAction<T>(this HttpClient client, string url, HttpContent content)
        {
            HttpResponseMessage response = await client.PostAsync(url, content);
            _ = response.EnsureSuccessStatusCode();
            return JsonUtil.Deserialize<Result<T>>(await response.Content.ReadAsStringAsync());
        }
 
        /// <summary>
        /// 下载文件保存到绝对路径
        /// </summary>
        /// <param name="client"></param>
        /// <param name="url"></param>
        /// <param name="absolutePath"></param>
        /// <param name="models"></param>
        public static async Task GetDownload(this HttpClient client, string url, string absolutePath, params object[] models)
        {
            foreach (object model in models)
            {
                url = url.ModelToUriParam(model);
            }
            HttpResponseMessage response = await client.GetAsync(url);
            int code = Convert.ToInt32(response.StatusCode);
            if (code == 200)
            {
                using (Stream stream = await response.Content.ReadAsStreamAsync())
                {
                    string suffix = Path.GetExtension(response.RequestMessage.RequestUri.ToString());
                    using (FileStream fs = new FileStream(absolutePath, FileMode.OpenOrCreate))
                    {
                        byte[] buffer = new byte[1024];
                        int readLength = 0;
                        int length;
                        while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                        {
                            readLength += length;
                            fs.Write(buffer, 0, length);
                        }
                    }
                }
            }
            else
            {
                string error = "图纸下载失败";
                if (response.Headers.TryGetValues("FileName", out IEnumerable<string> values))
                {
                    error = values.First();
                }
                throw new CustomWebException(error);
            }
        }
 
        /// <summary>
        /// 下载文件保存到绝对路径
        /// </summary>
        /// <param name="client"></param>
        /// <param name="url"></param>
        /// <param name="absolutePath"></param>
        /// <param name="models"></param>
        public static void GetDownloadSync(this HttpClient client, string url, string absolutePath, params object[] models)
        {
            foreach (object model in models)
            {
                url = url.ModelToUriParam(model);
            }
            Task<HttpResponseMessage> task = client.GetAsync(url);
            task.Wait();
            HttpResponseMessage response = task.Result;
            int code = Convert.ToInt32(response.StatusCode);
            if (code == 200)
            {
                Task<Stream> task2 = response.Content.ReadAsStreamAsync();
                task2.Wait();
                using (Stream stream = task2.Result)
                {
                    string suffix = Path.GetExtension(response.RequestMessage.RequestUri.ToString());
                    using (FileStream fs = new FileStream(absolutePath, FileMode.OpenOrCreate))
                    {
                        byte[] buffer = new byte[1024];
                        int readLength = 0;
                        int length;
                        while ((length = stream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            readLength += length;
                            fs.Write(buffer, 0, length);
                        }
                    }
                }
            }
            else
            {
                string error = "图纸下载失败";
                if (response.Headers.TryGetValues("FileName", out IEnumerable<string> values))
                {
                    error = HttpUtility.UrlDecode(values.First());
                }
                throw new CustomWebException(error);
            }
        }
 
        /// <summary>
        /// 下载文件到指定文件夹
        /// </summary>
        /// <param name="client"></param>
        /// <param name="url"></param>
        /// <param name="dir"></param>
        /// <param name="fileName"></param>
        /// <param name="models"></param>
        public static async Task GetDownload(this HttpClient client, string url, string dir, string fileName, params object[] models)
        {
            foreach (object model in models)
            {
                url = url.ModelToUriParam(model);
            }
            HttpResponseMessage response = await client.GetAsync(url);
            using (Stream stream = await response.Content.ReadAsStreamAsync())
            {
                string suffix = Path.GetExtension(response.RequestMessage.RequestUri.ToString());
                using (FileStream fs = new FileStream($"{dir}/{fileName}", FileMode.CreateNew))
                {
                    byte[] buffer = new byte[1024];
                    int readLength = 0;
                    int length;
                    while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                    {
                        readLength += length;
                        fs.Write(buffer, 0, length);
                    }
                }
            }
        }
 
        public static async void GetDownloadWithName(this HttpClient client, string url, string dir, params object[] models)
        {
            foreach (object model in models)
            {
                url = url.ModelToUriParam(model);
            }
 
            HttpResponseMessage response = await client.GetAsync(url);
            string fileName = HttpUtility.UrlDecode(response.Headers.GetValues("FileName").FirstOrDefault());
            using (Stream stream = await response.Content.ReadAsStreamAsync())
            {
                string suffix = Path.GetExtension(response.RequestMessage.RequestUri.ToString());
                using (FileStream fs = new FileStream($"{dir}/{fileName}", FileMode.CreateNew))
                {
                    byte[] buffer = new byte[1024];
                    int readLength = 0;
                    int length;
                    while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                    {
                        readLength += length;
                        fs.Write(buffer, 0, length);
                    }
                }
            }
        }
 
        public static string ModelToUriParam(this string url, object obj)
        {
            PropertyInfo[] properties = obj.GetType().GetProperties();
            StringBuilder sb = new StringBuilder()
                .Append(url).Append("?");
            if (obj is Dictionary<string, string>)
            {
                Dictionary<string, string> dict = (Dictionary<string, string>)obj;
                foreach (var item in dict)
                {
                    if (item.Value == null || string.IsNullOrWhiteSpace(item.Value))
                    {
                        continue;
                    }
                    sb = sb.Append(item.Key)
                       .Append("=")
                       .Append(HttpUtility.UrlEncode(item.Value))
                       .Append("&");
                }
            }
            else
            {
                foreach (PropertyInfo p in properties)
                {
                    object v = p.GetValue(obj, null);
                    if (v == null || string.IsNullOrWhiteSpace(v.ToString()))
                    {
                        continue;
                    }
                    sb = sb.Append(p.Name)
                        .Append("=")
                        .Append(HttpUtility.UrlEncode(v.ToString()))
                        .Append("&");
                }
            }
            sb = sb.Remove(sb.Length - 1, 1);
            return sb.ToString();
        }
    }
}