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方式使用成功

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM