C# HttpClient类库

示例代码:

 1 using System.Net.Http;
 2 using System.Net.Http.Headers;
 3 using System.Threading.Tasks;
 4 
 5 namespace MachineServer
 6 {
 7     public static class HttpHelper
 8     {
 9         public static HttpClient HttpClient { get; set; }
10 
11         public static void InitializeClient()
12         {
13             //单例模式
14             if (HttpClient == null)
15             {
16                 HttpClient = new HttpClient();
17             }
18 
19             HttpClient.DefaultRequestHeaders.Accept.Clear();
20             HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
21 
22             //能解读https类型
23             //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
24         }
25 
26         /// <summary>
27         /// Get方法
28         /// </summary>
29         /// <param name="url">目标链接(含参数)</param>
30         /// <returns>返回的字符串</returns>
31         public static async Task<string> GetAsync(string url)
32         {
33             using (HttpResponseMessage response = await HttpClient.GetAsync(url))
34             {
35                 response.EnsureSuccessStatusCode();
36                 string result = await response.Content.ReadAsStringAsync();
37                 return result;
38             }
39         }
40 
41         /// <summary>
42         /// Post方法
43         /// </summary>
44         /// <param name="url">目标链接</param>
45         /// <param name="json">发送的json格式的参数字符串</param>
46         /// <returns>返回的字符串</returns>
47         public static async Task<string> PostAsync(string url, string json)
48         {
49             StringContent content = new StringContent(json);
50             content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
51 
52             using (HttpResponseMessage response = await HttpClient.PostAsync(url, content))
53             {
54                 response.EnsureSuccessStatusCode();
55                 string result = await response.Content.ReadAsStringAsync();
56                 return result;
57             }
58         }
59 
60         /// <summary>
61         /// Post方法
62         /// </summary>
63         /// <param name="url">目标链接</param>
64         /// <param name="json">发送的json格式的参数字符串</param>
65         /// <returns>返回的字符串</returns>
66         public static async Task<string> PostAsync(string url, HttpContent content)
67         {
68             //HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>()
69             //       {
70             //           { "token", token},
71             //           { "orderNo", orderNo}
72             //       });
73             content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };
74 
75             using (HttpResponseMessage response = await HttpClient.PostAsync(url, content))
76             {
77                 response.EnsureSuccessStatusCode();
78                 string result = await response.Content.ReadAsStringAsync();
79                 return result;
80             }
81         }
82     }
83 }

Get方法

get方法传递参数,是将参数及其值直接跟在url后面,以?开始,中间用&间隔,类似:

string tokenString = await HttpHelper.GetAsync($"https://er.com/Apps/Mes/getToken?appKey=11&nonce=22&timestamp=33&signature=44");

Post方法

post方法传递参数有几种形式,需要看HTTP服务端那边支持哪种,客户端用时,需要将Header的ContentType设置正确。

总结以下三种:

1. json格式:

content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

对应Postman中:

2. form-data格式:

content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundarypy5dIaqJBcHjn7sv");

对应Postman中:

3. x-www-form-urlencoded格式:

content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };

对应Postman中:

已测试Post方法的x-www-form-urlencoded方式使用成功

原文地址:https://www.cnblogs.com/zwh1993/p/13598154.html