• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#HttpClient类库

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 

示例代码:

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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
【CSharp】C#开发ActiveX插件发布时间:2022-07-18
下一篇:
C#SocketUDP案例3异步发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap