WPF开发-网络请求、接口请求、文件上传

对比

三者从封装程度从低到高依次为

HttpWebRequest=>WebClient=>HttpClient

区别

HttpWebRequset WebClient HttpClient
命名空间 System.Net System.Net System.Net.Http
继承类 WebRequest Component HttpMessageInvoker
支持url转向
支持cookie和session
支持用户代理服务器
使用复杂度

HttpWebRequest

这是.NET创建者最初开发用于使用HTTP请求的标准类。

使用HttpWebRequest可以让开发者控制请求/响应流程的各个方面,如 timeouts, cookies, headers, protocols。

另一个好处是HttpWebRequest类不会阻塞UI线程。例如,当您从响应很慢的API服务器下载大文件时,您的应用程序的UI不会停止响应。

HttpWebRequest通常和WebResponse一起使用,一个发送请求,一个获取数据。

HttpWebRquest更为底层一些,能够对整个访问过程有个直观的认识,但同时也更加复杂一些。以GET请求为例,至少需要五行代码才能够实现。

1
2
3
4
5
6
7
HttpWebRequest http = (HttpWebRequest)WebRequest.Create("http://example.com");
WebResponse response = http.GetResponse();
Stream stream = response.GetResponseStream();
using (var streamtemn = File.Create("路径"))
{
stream.CopyTo(streamtemn);
}

工具类

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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
namespace Z.Utils.Common
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;

public class ZHttpUtil
{
public static string tokenKey = "";
public static string tokenValue = "";
public static string userId = "";
public static string version = "";
public static bool isSt;

public static bool GetNetStatus()
{
System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
try
{
System.Net.NetworkInformation.PingReply ret = ping.Send("www.baidu.com");
return ret is { Status: System.Net.NetworkInformation.IPStatus.Success };
}
catch (Exception)
{
return false;
}
}

/// <summary>
/// 获取Form请求的参数
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
public static string GetParas(Dictionary<string, object> dic)
{
List<string> allPara = new List<string>();
foreach (KeyValuePair<string, object> keyValuePair in dic)
{
allPara.Add(keyValuePair.Key + "=" + keyValuePair.Value);
}
return string.Join(
"&",
allPara
);
}

/// <summary>
/// Get http请求
/// </summary>
/// <param name="url">
/// 请求地址
/// </param>
/// <param name="jm">加密</param>
/// <param name="timeout">
/// 超时时间
/// </param>
/// <param name="encode">
/// 编码
/// </param>
/// <returns>
/// 返回单个实体
/// </returns>
public static T GetSingle<T>
(
string url,
bool jm = true,
int timeout = 5000,
string encode = "UTF-8"
) where T : class
{
if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(encode))
{
return default;
}
try
{
string respStr = GetStr(
url,
jm,
timeout,
encode
);
return ZJsonHelper.JsonToObj<T>(respStr);
}
catch (Exception)
{
// ignored
}
return default;
}

/// <summary>
/// Post Http请求
/// </summary>
/// <param name="url">
/// 请求地址
/// </param>
/// <param name="postData">
/// 传输数据
/// </param>
/// <param name="jm">是否加密</param>
/// <param name="timeout">
/// 超时时间
/// </param>
/// <param name="contentType">
/// 媒体格式
/// </param>
/// <param name="encode">
/// 编码
/// </param>
/// <returns>
/// 泛型集合
/// </returns>
public static T PostSignle<T>
(
string url,
string postData = "",
bool jm = true,
int timeout = 5000,
string contentType = "application/json",
string encode = "UTF-8"
) where T : class
{
if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(encode) && !string.IsNullOrEmpty(contentType) && postData != null)
{
try
{
string respstr = PostStr(
url,
postData,
jm,
timeout,
contentType,
encode
);
return ZJsonHelper.JsonToObj<T>(respstr);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return default;
}

/// <summary>
/// Post Http请求
/// </summary>
/// <param name="url">
/// 请求地址
/// </param>
/// <param name="postData">
/// 传输数据
/// </param>
/// <param name="jm">加密</param>
/// <param name="timeout">
/// 超时时间
/// </param>
/// <param name="contentType">
/// 媒体格式
/// </param>
/// <param name="encode">
/// 编码
/// </param>
/// <returns>
/// 泛型集合
/// </returns>
public static List<T> PostList<T>
(
string url,
string postData,
bool jm = true,
int timeout = 5000,
string contentType = "application/json",
string encode = "UTF-8"
)
{
if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(encode) && !string.IsNullOrEmpty(contentType) && postData != null)
{
try
{
string respstr = PostStr(
url,
postData,
jm,
timeout,
contentType,
encode
);
return ZJsonHelper.JsonToList<T>(respstr);
}
catch (Exception)
{
// ignored
}
}
return null;
}

private static void AddHeader(HttpWebRequest webRequest)
{
webRequest.Headers.Add(
"Xh-St",
isSt ? "true" : "false"
);
if (!string.IsNullOrEmpty(tokenKey) && !string.IsNullOrEmpty(tokenValue))
{
webRequest.Headers.Add(
"Xh-Token-Key",
tokenKey
);
webRequest.Headers.Add(
"Xh-Token-Value",
tokenValue
);
}
if (!string.IsNullOrEmpty(userId))
{
webRequest.Headers.Add(
"Xh-User-Id",
userId
);
}
webRequest.Headers.Add(
"Xh-Device",
"class_pc_t"
);
webRequest.Headers.Add(
"Xh-Version",
version
);
}

/// <summary>
/// Get请求
/// </summary>
/// <param name="url"></param>
/// <param name="jm">加密</param>
/// <param name="timeout"></param>
/// <param name="encode"></param>
/// <returns></returns>
private static string GetStr
(
string url,
bool jm = true,
int timeout = 5000,
string encode = "UTF-8"
)
{
Stream responseStream = null;
StreamReader streamReader = null;
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
if (jm)
{
AddHeader(webRequest);
}
webRequest.Method = "GET";
webRequest.Timeout = timeout;
WebResponse webResponse = webRequest.GetResponse();
responseStream = webResponse.GetResponseStream();
if (responseStream == null) { return ""; }
streamReader = new StreamReader(
responseStream,
Encoding.GetEncoding(encode)
);
return streamReader.ReadToEnd();
}
catch (Exception)
{
return "";
}
finally
{
if (streamReader != null)
{
streamReader.Dispose();
}
if (responseStream != null)
{
responseStream.Dispose();
}
}
}

public static string PostStr
(
string url,
string postData,
bool jm = true,
int timeout = 60000,
string contentType = "application/json;",
string encode = "UTF-8"
)
{
Stream requestStream = null;
Stream responseStream = null;
StreamReader streamReader = null;
try
{
string aesPostData = postData;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
if (jm)
{
if (isSt)
{
aesPostData = AesHelper.AesEncrypt(
postData,
"XINGHUOLIAOYUAN7"
);
}
AddHeader(webRequest);
}
byte[] data = Encoding.GetEncoding(encode).GetBytes(aesPostData);
webRequest.Method = "POST";
webRequest.ContentType = contentType + ";" + encode;
webRequest.ContentLength = data.Length;
webRequest.Timeout = timeout;
webRequest.MaximumAutomaticRedirections = 1; //请求最大次数
requestStream = webRequest.GetRequestStream();
requestStream.Write(
data,
0,
data.Length
);
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
//响应头中获取是否加密
isSt = webResponse.GetResponseHeader("Xh-St") == "true";
responseStream = webResponse.GetResponseStream();
if (responseStream == null) { return ""; }
streamReader = new StreamReader(
responseStream,
Encoding.GetEncoding(encode)
);
return streamReader.ReadToEnd();
}
catch (Exception)
{
return "";
}
finally
{
if (streamReader != null)
{
streamReader.Dispose();
}
if (responseStream != null)
{
responseStream.Dispose();
}
if (requestStream != null)
{
requestStream.Dispose();
}
}
}

public static string UploadFile
(
string url,
string filePath,
string paramName,
NameValueCollection nvc
)
{
string contentType = filePath.Substring(
filePath.LastIndexOf(
".",
StringComparison.Ordinal
) +
1
);
string filename = filePath.Substring(
filePath.LastIndexOf(
"\\",
StringComparison.Ordinal
) +
1
);
string boundary = "-----" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = CredentialCache.DefaultCredentials;
WebResponse wresp = null;
try
{
Stream rs = wr.GetRequestStream();
const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(
boundarybytes,
0,
boundarybytes.Length
);
string formitem = string.Format(
formdataTemplate,
key,
nvc[key]
);
byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
rs.Write(
formitembytes,
0,
formitembytes.Length
);
}
rs.Write(
boundarybytes,
0,
boundarybytes.Length
);
const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(
headerTemplate,
paramName,
filename,
contentType
);
byte[] headerbytes = Encoding.UTF8.GetBytes(header);
rs.Write(
headerbytes,
0,
headerbytes.Length
);
FileStream fileStream = new FileStream(
filePath,
FileMode.Open,
FileAccess.Read
);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileStream.Read(
buffer,
0,
buffer.Length
)) !=
0)
{
rs.Write(
buffer,
0,
bytesRead
);
}
fileStream.Close();
byte[] trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(
trailer,
0,
trailer.Length
);
rs.Close();
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
if (stream2 != null)
{
StreamReader reader2 = new StreamReader(stream2);
string xmlDoc = reader2.ReadToEnd();
return xmlDoc;
}
return null;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if (wresp != null)
{
wresp.Close();
}
return null;
}
}

/// <summary>
/// 上传文件流
/// </summary>
/// <param name="url">URL</param>
/// <param name="databyte">文件数据流</param>
/// <param name="filename">文件名</param>
/// <param name="formFields">参数 可不传</param>
public static T UploadRequestflow<T>
(
string url,
byte[] databyte,
string filename,
NameValueCollection formFields = null
) where T : class
{
// 时间戳,用做boundary
string boundary = "-----" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

//根据uri创建HttpWebRequest对象
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
httpReq.ContentType = "multipart/form-data; boundary=" + boundary;
httpReq.Method = "POST";
httpReq.KeepAlive = true;
//httpReq.Timeout = 300000;
//httpReq.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存
httpReq.Credentials = CredentialCache.DefaultCredentials;
try
{
Stream postStream = httpReq.GetRequestStream();
//参数
const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
if (formFields != null)
{
foreach (string key in formFields.Keys)
{
postStream.Write(
boundarybytes,
0,
boundarybytes.Length
);
string formitem = string.Format(
formdataTemplate,
key,
formFields[key]
);
byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
postStream.Write(
formitembytes,
0,
formitembytes.Length
);
}
}
postStream.Write(
boundarybytes,
0,
boundarybytes.Length
);
const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";

//文件头
string header = string.Format(
headerTemplate,
"file",
filename
);
byte[] headerbytes = Encoding.UTF8.GetBytes(header);
postStream.Write(
headerbytes,
0,
headerbytes.Length
);

//文件流
postStream.Write(
databyte,
0,
databyte.Length
);

//结束边界
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
postStream.Write(
boundaryBytes,
0,
boundaryBytes.Length
);
postStream.Close();

//获取服务器端的响应
T jobResult;
using (HttpWebResponse response = (HttpWebResponse)httpReq.GetResponse())
{
Stream receiveStream = response.GetResponseStream();
if (receiveStream != null)
{
StreamReader readStream = new StreamReader(
receiveStream,
Encoding.UTF8
);
string returnValue = readStream.ReadToEnd();
jobResult = ZJsonHelper.JsonToObj<T>(returnValue);
response.Close();
readStream.Close();
}
else
{
return null;
}
}
return jobResult;
}
catch (Exception)
{
return default;
}
}
}
}

Nuget中安装Newtonsoft.Json

JSON转换类

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
using Newtonsoft.Json;

using System.Collections.Generic;
using System.IO;

namespace Z.Common
{
public class ZJsonHelper
{
#region Method

/// <summary>
/// 类对像转换成json格式
/// </summary>
/// <returns>
/// </returns>
public static string ToJson(object t)
{
return JsonConvert.SerializeObject(
t, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include }
);
}

/// <summary>
/// 类对像转换成json格式
/// </summary>
/// <param name="t">
/// </param>
/// <param name="HasNullIgnore">
/// 是否忽略NULL值
/// </param>
/// <returns>
/// </returns>
public static string ToJson(object t, bool HasNullIgnore)
{
if (HasNullIgnore)
{
return JsonConvert.SerializeObject(t, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
}
else
{
return ToJson(t);
}
}

/// <summary>
/// json格式转换
/// </summary>
/// <typeparam name="T">
/// </typeparam>
/// <param name="strJson">
/// </param>
/// <returns>
/// </returns>
public static T JsonToObj<T>(string strJson) where T : class
{
if (strJson != null && strJson != "") { return JsonConvert.DeserializeObject<T>(strJson); }

return null;
}

internal static List<T> JsonToList<T>(string respstr)
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(respstr);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
List<T> list = o as List<T>;
return list;
}

#endregion Method
}
}

AES加密

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
namespace Z.Utils.Common
{
using System;
using System.Security.Cryptography;
using System.Text;

/// <summary>
/// AES加密
/// </summary>
public class AesHelper
{
public static string QrcodeLoginKey = "zyyxhlywkdatakey";

/// <summary>
/// AES 加密
/// </summary>
/// <returns>
/// Encrypted 16 hex string
/// </returns>
public static string AesEncrypt(string data, string key = "")
{
if (string.IsNullOrWhiteSpace(key))
{
key = QrcodeLoginKey.PadRight(16, '0');
}

// 256-AES key
byte[] keyArray = Encoding.UTF8.GetBytes(key);
byte[] toEncryptArray = Encoding.UTF8.GetBytes(data);

RijndaelManaged rDel = new RijndaelManaged
{
Key = keyArray,
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};

ICryptoTransform cTransform = rDel.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0,
toEncryptArray.Length);

return BytesToHexString(resultArray);
}

/// <summary>
/// AES 解密
/// </summary>
/// <param name="hexString">
/// Encrypted 16 hex string
/// </param>
/// <param name="key"></param>
/// <returns>
/// Decrypted string
/// </returns>
public static string AesDecrypt(string hexString, string key = "")
{
if (string.IsNullOrWhiteSpace(key))
{
key = QrcodeLoginKey.PadRight(16, '0');
}

// 256-AES key
byte[] keyArray = Encoding.ASCII.GetBytes(key);
byte[] toEncryptArray = HexStringToBytes(hexString);

RijndaelManaged rDel = new RijndaelManaged
{
Key = keyArray,
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};

ICryptoTransform cTransform = rDel.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0,
toEncryptArray.Length);

return Encoding.ASCII.GetString(resultArray);
}

/// <summary>
/// Byte array to convert 16 hex string
/// </summary>
/// <param name="bytes">
/// byte array
/// </param>
/// <returns>
/// 16 hex string
/// </returns>
public static string BytesToHexString(byte[] bytes)
{
StringBuilder returnStr = new StringBuilder();
if (bytes != null)
{
foreach (var t in bytes)
{
returnStr.Append(t.ToString("X2"));
}
}
return returnStr.ToString();
}

/// <summary>
/// 16 hex string converted to byte array
/// </summary>
/// <param name="hexString">
/// 16 hex string
/// </param>
/// <returns>
/// byte array
/// </returns>
public static byte[] HexStringToBytes(string hexString)
{
if (hexString == null || hexString.Equals(""))
{
return null;
}
int length = hexString.Length / 2;
if (hexString.Length % 2 != 0)
{
return null;
}
byte[] d = new byte[length];
for (int i = 0; i < length; i++)
{
d[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return d;
}
}
}

接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static async Task<ResultVo<string>> GetMN(string mac)
{
return await Task.Run(
() =>
{
try
{
string url = ZConfig.apiAddress + "/sexam/eb/get_mn";//地址
Dictionary<string, object> dic = new Dictionary<string, object> { { "mac", mac } };
string body = ZJsonHelper.ToJson(dic);
ResultVo<string> result = ZHttpUtil.PostAndRespSignle<ResultVo<string>>(url, postData: body);
return result;
}
catch (Exception)
{
return new ResultVo<string> { code = 1, msg = "接口请求失败!" };
}
}
);
}

文件上传调用

1
2
3
4
var dic = new NameValueCollection();

var resp = ZHttpUtil.UploadFile(url, zipPath, "file", dic);
var result = ZJsonHelper.JsonToObj<ResultVo<string>>(resp);

文件下载带进度

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
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Threading;

namespace SchoolClient.Utils
{
internal class ZJDownloadUtil
{
public static void downloadFile(string url, string savepath)
{
string path = savepath;
string filename = url.Substring(url.LastIndexOf("/") + 1);
if (!url.StartsWith("http") || filename == null || filename == "")
{
return;
}
path += filename;
// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream responseStream = response.GetResponseStream();

//创建本地文件写入流
Stream stream = new FileStream(path, FileMode.Create);

byte[] bArr = new byte[1024];
int size = responseStream.Read(bArr, 0, bArr.Length);
while (size > 0)
{
stream.Write(bArr, 0, size);
size = responseStream.Read(bArr, 0, bArr.Length);
}
stream.Close();
responseStream.Close();
}

/// <summary>
/// Http下载文件
/// </summary>
public static Thread downloadFileWithCallback(
string url,
int tag,
string savepath,
Dispatcher dispatcher,
ZJDownloadCallback callback
)
{
string path = savepath;
string filename = url.Substring(url.LastIndexOf("/") + 1);
path += filename;
if (!url.StartsWith("http") || filename == null || filename == "")
{
return null;
}
Thread thread = new Thread(
o =>
{
FileInfo fi = new FileInfo(path);
if (fi.Exists)
{
dispatcher.Invoke(
new Action(
() =>
{
callback.downloadEnd(tag, path);
}));
}
else
{
string temppath = path + ".tmp";
if (File.Exists(temppath))
{
temppath += "1";
while (File.Exists(temppath))
{
temppath += "1";
if (!File.Exists(temppath))
{
break;
}
}
}

dispatcher.Invoke(
new Action(
() =>
{
callback.downloadBegin(tag);
}));

try
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream responseStream = response.GetResponseStream();

//创建本地文件写入流
Stream stream = new FileStream(temppath, FileMode.Create);
long totalSize = response.ContentLength;
byte[] bArr = new byte[1024];
int size = responseStream.Read(bArr, 0, bArr.Length);
long readsize = 0;
while (size > 0)
{
readsize += size;
stream.Write(bArr, 0, size);
size = responseStream.Read(bArr, 0, bArr.Length);

dispatcher.Invoke(
new Action(
() =>
{
callback.downloadProgress(tag, (int)(readsize * 100 / totalSize));
}));
}
stream.Close();
responseStream.Close();
FileInfo fitemp = new FileInfo(temppath);
fitemp.MoveTo(path);
dispatcher.Invoke(
new Action(
() =>
{
callback.downloadEnd(tag, path);
}));
}
catch (Exception ex)
{
dispatcher.Invoke(new Action(
() =>
{
callback.downloadError(tag, ex.Message);
}));
}
}
});
thread.Start();
return thread;
}

public static void downloadFileWithCallback(
string url,
string path,
int tag,
Dispatcher dispatcher,
ZJDownloadCallback callback
)
{
downloadFileWithCallback(url, tag, path, dispatcher, callback);
}

public interface ZJDownloadCallback
{
/// <summary>
/// 下载开始
/// </summary>
/// <param name="tag"></param>
void downloadBegin(int tag);

/// <summary>
/// 下载过程
/// </summary>
/// <param name="tag"></param>
/// <param name="progress"></param>
void downloadProgress(int tag, int progress);

/// <summary>
/// 下载结束
/// </summary>
/// <param name="tag"></param>
/// <param name="filepath"></param>
void downloadEnd(int tag, string filepath);

/// <summary>
/// 下载结束
/// </summary>
/// <param name="tag"></param>
/// <param name="filepath"></param>
void downloadError(int tag, string msg);
}
}
}

这种方法是早期开发者使用的方法,在当前业务中已经很少使用,由于其更加底层,需要处理一些细节,最多可用于框架内部操作。

WebClient(不推荐)

是一种更高级别的抽象,相当于封装了request和response方法

WebClient是一种更高级别的抽象,是HttpWebRequest为了简化最常见任务而创建的,使用过程中你会发现他缺少基本的header,timeoust的设置,不过这些可以通过继承httpwebrequest来实现。

相对来说,WebClient比WebRequest更加简单,它相当于封装了request和response方法,不过需要说明的是,Webclient和WebRequest继承的是不同类,两者在继承上没有任何关系。

使用WebClient可能比HttpWebRequest直接使用更慢(大约几毫秒),但却更为简单,减少了很多细节,代码量也比较少,比如下载文件的代码,只需要两行。

1
2
3
4
using (WebClient webClient = new WebClient())
{
webClient.DownloadFile("http://example.com", "路径");
}

WebClient主要面向了WEB网页场景,在模拟Web操作时使用较为方便,但用在RestFul场景下却比较麻烦,这时候就需要HttpClient出马了。

HttpClient(推荐)

HttpClient是.NET4.5引入的一个HTTP客户端库

目前业务上使用的比较多的是HttpClient,它适合用于多次请求操作,一般设置好默认头部后,可以进行重复多次的请求,基本上用一个实例可以提交任何的HTTP请求。此外,HttpClient提供了异步支持,可以轻松配合async await实现异步请求。

调用发现没有ReadAsAsync方法

1
Install-Package Microsoft.AspNet.WebApi.Client

原因是

这个方法原来是在这个包里的 System.Net.Http.Formatting ,但是它已经废弃了。

我们可以在NuGet中找到 Microsoft.AspNet.WebApi.Client 作为替代。

工具类

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
namespace Z.Utils.Common
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Handlers;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

public class ZHttpAsyncUtil
{
#region GET请求无参数

/// <summary>
/// GET请求无参数--异步方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static async Task<T> GetAsync<T>(string url)
{
using (HttpClient client = new HttpClient())
{
//基地址/域名
//client.BaseAddress = new Uri(BaseUri);
//设定传输格式为json
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsAsync<T>();
}
return default(T);
}
}

#endregion GET请求无参数

#region GET请求

/// <summary>
/// GET请求--异步方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="param">参数</param>
/// <returns></returns>
public static async Task<T> GetAsync<T>(string url, Dictionary<string, string> param)
{
using (HttpClient client = new HttpClient())
{
//设定传输格式为json
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
//client.DefaultRequestHeaders.Add("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");

StringBuilder strUri = new StringBuilder();
//方法
strUri.AppendFormat("{0}?", url);
//参数
if (param.Count > 0)
{
foreach (KeyValuePair<string, string> pair in param)
{
strUri.AppendFormat("{0}={1}&&", pair.Key, pair.Value);
}
strUri.Remove(strUri.Length - 2, 2); //去掉'&&'
}
else
{
strUri.Remove(strUri.Length - 1, 1); //去掉'?'
}
HttpResponseMessage response = await client.GetAsync(strUri.ToString());
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsAsync<T>();
}
return default(T);
}
}

#endregion GET请求

#region POST请求

/// <summary>
/// POST请求--异步方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="param">参数</param>
/// <returns></returns>
public static async Task<T> PostAsync<T>(string url, object param)
{
using (HttpClient client = new HttpClient())
{
//基地址/域名
//client.BaseAddress = new Uri(BaseUri);
//设定传输格式为json
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = await client.PostAsync(url, param, new JsonMediaTypeFormatter());
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsAsync<T>();
}
return default(T);
}
}

#endregion POST请求

#region 文件上传

/// <summary>
/// 文件上传 含参数
/// </summary>
/// <param name="url"></param>
/// <param name="filePaths"></param>
/// <param name="param"></param>
/// <returns></returns>
public static async Task<T> UploadAsync<T>(string url, Dictionary<string, string> filePaths,
Dictionary<string, string> param)
{
using HttpClient client = new HttpClient();
using var content = new MultipartFormDataContent();
//基地址/域名
//client.BaseAddress = new Uri(BaseUri);
foreach (var filePath in filePaths)
{
var fileContent = new ByteArrayContent(File.ReadAllBytes(filePath.Key));
fileContent.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment") { FileName = filePath.Value };
content.Add(fileContent);
}

foreach (var pair in param)
{
var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(pair.Value));
dataContent.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment") { Name = pair.Key };
content.Add(dataContent);
}

HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsAsync<T>();
}

return default(T);
}

#endregion 文件上传

#region 下载文件

/// <summary>
/// 下载文件
/// </summary>
/// <param name="url"></param>
/// <param name="filePath">要保存到本地的路径全名 如:C://Download/close.png</param>
/// <returns></returns>
public static async Task<bool> DownloadFile(string url, string filePath)
{
try
{
using (var client = new HttpClient())
using (var filestream = new FileStream(filePath, FileMode.Create))
{
var netstream = await client.GetStreamAsync(url);
await netstream.CopyToAsync(filestream);//写入文件
}
return true;
}
catch
{
return false;
}
}

#endregion 下载文件

#region 下载文件 带进度条

/// <summary>
/// 下载网络文件 带进度条 显示当前进度
/// </summary>
/// <param name="url"></param>
/// <param name="filePath">下载完成后的文件名</param>
/// <param name="httpReceiveProgress"></param>
/// <returns></returns>
public static async Task<bool> DownloadFile(
string url,
string filePath,
EventHandler<HttpProgressEventArgs> httpReceiveProgress
)
{
try
{
var progressMessageHandler = new ProgressMessageHandler(new HttpClientHandler());
progressMessageHandler.HttpReceiveProgress += httpReceiveProgress;
using (var client = new HttpClient(progressMessageHandler))
using (var filestream = new FileStream(filePath, FileMode.Create))
{
var netstream = await client.GetStreamAsync(url);
await netstream.CopyToAsync(filestream);//写入文件
}
return true;
}
catch
{
return false;
}
}

#endregion 下载文件 带进度条
}
}

POST请求

1
var result = await ZHttpAsyncUtil.PostAsync<ResultVo<AppModel>>(url, new Dictionary<string, string>());

下载带进度

1
2
3
4
5
6
7
8
_ = ZHttpAsyncUtil.DownloadFile(
fileUrl,
ZConfig.tempAppPath + "test.exe",
(s, e) =>
{
Console.WriteLine("进度:" + e.ProgressPercentage + "%");
}
);

文件分片上传

上传

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
/// <summary>
/// 上传文件流
/// </summary>
/// <param name="url">URL</param>
/// <param name="databyte">文件数据流</param>
/// <param name="filename">文件名</param>
/// <param name="formFields">参数 可不传</param>
public static JObject UploadRequestflow(string url, byte[] databyte, string filename, NameValueCollection formFields = null)
{
JObject jobResult = null;
// 时间戳,用做boundary
string boundary = "-----" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

//根据uri创建HttpWebRequest对象
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
httpReq.ContentType = "multipart/form-data; boundary=" + boundary;
httpReq.Method = "POST";
httpReq.KeepAlive = true;
//httpReq.Timeout = 300000;
//httpReq.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存
httpReq.Credentials = CredentialCache.DefaultCredentials;

try
{
Stream postStream = httpReq.GetRequestStream();
//参数
const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
if (formFields != null)
{
foreach (string key in formFields.Keys)
{
postStream.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, formFields[key]);
byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
postStream.Write(formitembytes, 0, formitembytes.Length);
}
}
postStream.Write(boundarybytes, 0, boundarybytes.Length);

const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";

//文件头
string header = string.Format(headerTemplate, "file", filename);
byte[] headerbytes = Encoding.UTF8.GetBytes(header);
postStream.Write(headerbytes, 0, headerbytes.Length);

//文件流
postStream.Write(databyte, 0, databyte.Length);

//结束边界
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
postStream.Close();

//获取服务器端的响应
using (HttpWebResponse response = (HttpWebResponse)httpReq.GetResponse())
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
string returnValue = readStream.ReadToEnd();
jobResult = JObject.Parse(returnValue);
response.Close();
readStream.Close();
}
return jobResult;
}
catch (Exception ex)
{
LogHelper.WriteErrLog("【文件上传】" + ex.Message, ex);
return null;
}
finally
{
}
}

调用

1
2
3
4
5
6
7
8
NameValueCollection formFields = new NameValueCollection
{
{ "identifier", identifier },
{ "chunkNumber",chunkNumber },
{ "filename", fileName },
{ "totalchunk", totalchunk },
{ "md5", md5 }
};

获取文件大小

1
2
3
4
5
6
7
8
9
10
11
12
/// <summary>  
/// 获取一个文件的长度,单位为Byte
/// </summary>
/// <param name="filePath">文件的绝对路径</param>
public static long GetFileSize(string filePath)
{
//创建一个文件对象
FileInfo fi = new FileInfo(filePath);

//获取文件的大小
return fi.Length;
}

读取文件分片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/// <summary>
/// 读取指定长度的流
/// </summary>
/// <param name="filePath">文件位置</param>
/// <param name="startIndex">开始位置</param>
/// <param name="Length">长度</param>
/// <returns></returns>
public static byte[] ReadBigFileSpecifyLength(string filePath, long startIndex, int Length)
{
FileStream stream = new FileStream(filePath, FileMode.Open);
if (startIndex + Length + 1 > stream.Length)
{
Length = (int)(stream.Length - startIndex);
}
byte[] buffer = new byte[Length];
stream.Position = startIndex;
stream.Read(buffer, 0, Length);
stream.Close();
stream.Dispose();
return buffer;
}

获取byte[]的MD5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static string GetMD5Hash(byte[] bytedata)
{
try
{
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(bytedata);

StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
catch (Exception ex)
{
throw new Exception("获取MD5失败:" + ex.Message);
}
}

注意点

接口地址拼接

我们直接拼接的时候可能中间的分隔符会重复或缺少,所以建议用下面的方式处理。

1
string url = new Uri(new Uri(ZConfig.uploadUrl), "/chunkdb/isexist").AbsoluteUri;

请求参数

Form请求参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/// <summary>
/// 获取Form请求的参数
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
public static string GetParas(Dictionary<string, object> dic)
{
List<string> allPara = new List<string>();
foreach (KeyValuePair<string, object> keyValuePair in dic)
{
allPara.Add(keyValuePair.Key + "=" + keyValuePair.Value);
}

return string.Join("&", allPara);
}

contentType

表单

1
contentType: "application/x-www-form-urlencoded;charset:utf-8;"

JSON

1
contentType: "application/json;"

表单文件上传

1
contentType: "multipart/form-data;"

获取网络是否可用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static bool GetNetStatus()
{
System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
try
{
System.Net.NetworkInformation.PingReply ret = ping.Send("www.baidu.com");
if (ret != null && ret.Status == System.Net.NetworkInformation.IPStatus.Success)
{
//有网
return true;
}
//无网
return false;
}
catch (Exception)
{
return false;
}
}