当前位置:   article > 正文

C# Http 请求接口 Get / Post_c# http post

c# http post

目录

一、概述

二、创建 Web API 

三、HttpRequestHelper

三、测试

结束


一、概述

get 和 post 请求,最早被用来做浏览器与服务器之间交互HTML和表单的通讯协议,后来又被广泛的扩充到接口格式的定义上,到目前为止,get / post 请求依然应用在各大网站中,比如在用户登录时,调用 get / post 请求将用户名、密码传到服务器,由服务器进行判断,是否允许用户登录,再将结果返回给浏览器,这样就实现了登录的功能。在后期的 pc 软件开发中,get / post 请求偶尔也会用到,做为一个程序员,http 协议也是我们必须要学的知识点。

二、创建 Web API 

如果你只是想参考 Get Post 请求方法,请跳过当前章节

其实 Get Post 请求不光是 Java、PHP 等语言的专利,C# 也可以实现,下面用 C# 大致演示下 web api 的开发流程。

创建 一个 web api 项目,用作后面测试用的接口,关于 Web API  怎么创建项目的,可以参考我之前写的教程:

C# ASP.NET Web Core API (.NET 6.0)_熊思宇的博客-CSDN博客

按上面教程,添加一个 ValuesController 接口后,我这里稍做一些更改

默认:

修改后:

 将默认添加的天气预报相关的两个类删除

launchSettings.json 配置如下,在 applicationUrl 这里,你的可能和我的不一样,这个是对外访问的链接,有两个接口,一个是 https,一个是 http,端口号不一样,ip 部分是用来限制登录的,如果开发所有人,就用 0.0.0.0 代替

  1. {
  2. "$schema": "https://json.schemastore.org/launchsettings.json",
  3. "iisSettings": {
  4. "windowsAuthentication": false,
  5. "anonymousAuthentication": true,
  6. "iisExpress": {
  7. "applicationUrl": "http://localhost:10090",
  8. "sslPort": 44385
  9. }
  10. },
  11. "profiles": {
  12. "WebApplication1": {
  13. "commandName": "Project",
  14. "dotnetRunMessages": true,
  15. "launchBrowser": false,
  16. "launchUrl": "swagger",
  17. "applicationUrl": "https://localhost:7281;http://localhost:5252",
  18. "environmentVariables": {
  19. "ASPNETCORE_ENVIRONMENT": "Development"
  20. }
  21. },
  22. "IIS Express": {
  23. "commandName": "IISExpress",
  24. "launchBrowser": true,
  25. "launchUrl": "swagger",
  26. "environmentVariables": {
  27. "ASPNETCORE_ENVIRONMENT": "Development"
  28. }
  29. }
  30. }
  31. }

将 ValuesController 代码修改如下

  1. using Microsoft.AspNetCore.Mvc;
  2. namespace WebApplication1.Controllers
  3. {
  4. [ApiController]
  5. [Route("[controller]")]
  6. public class ValuesController : ControllerBase
  7. {
  8. [HttpGet]
  9. public IEnumerable<string> Get()
  10. {
  11. return new string[] { "value1", "value2" };
  12. }
  13. [HttpGet("{id}")]
  14. public string Get(int id)
  15. {
  16. return "value";
  17. }
  18. [HttpPost]
  19. public string Post([FromForm] string json)
  20. {
  21. Console.WriteLine(json);
  22. return "hello, good afternoon";
  23. }
  24. }
  25. }

启动项目,接下来用 Postman 进行测试

1. Get 接口

2.Post 接口

返回了对应的结果,就是成功了 

三、HttpRequestHelper

新建一个控制台项目,添加一个类 HttpRequestHelper,第一个版本是一些传统的写法,后面我又做了一点优化,优化的版本在本章节的最下面,这两个版本都可以做参考。

HttpRequestHelper 代码

  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Net;
  6. using System.Net.Http;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. /// <summary>
  10. /// http请求
  11. /// </summary>
  12. public class HttpRequestHelper
  13. {
  14. #region Get
  15. /// <summary>
  16. /// Get请求
  17. /// </summary>
  18. /// <param name="url">请求url</param>
  19. /// <returns></returns>
  20. public static string Get(string url)
  21. {
  22. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  23. req.Method = "GET";
  24. req.Timeout = 3000;
  25. if (req == null || req.GetResponse() == null)
  26. return string.Empty;
  27. HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  28. if (resp == null)
  29. return string.Empty;
  30. using (Stream stream = resp.GetResponseStream())
  31. {
  32. using (StreamReader reader = new StreamReader(stream))
  33. {
  34. return reader.ReadToEnd();
  35. }
  36. }
  37. }
  38. /// <summary>
  39. /// Get请求
  40. /// </summary>
  41. /// <param name="url"></param>
  42. /// <param name="headerKey"></param>
  43. /// <param name="headerValue"></param>
  44. /// <returns></returns>
  45. public static string Get(string url, string headerKey, string headerValue)
  46. {
  47. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  48. req.Method = "GET";
  49. req.Timeout = 3000;
  50. req.Headers[headerKey] = headerValue;
  51. if (req == null || req.GetResponse() == null)
  52. return string.Empty;
  53. HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  54. if (resp == null)
  55. return string.Empty;
  56. using (Stream stream = resp.GetResponseStream())
  57. {
  58. using (StreamReader reader = new StreamReader(stream))
  59. {
  60. return reader.ReadToEnd();
  61. }
  62. }
  63. }
  64. #endregion
  65. #region Post
  66. /// <summary>
  67. /// Post请求
  68. /// </summary>
  69. /// <param name="url">接口url</param>
  70. /// <returns></returns>
  71. public static string Post(string url)
  72. {
  73. string result = string.Empty;
  74. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  75. req.Method = "POST";
  76. req.Timeout = 3000;
  77. HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  78. Stream stream = resp.GetResponseStream();
  79. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  80. {
  81. result = reader.ReadToEnd();
  82. }
  83. return result;
  84. }
  85. /// <summary>
  86. /// Post请求
  87. /// </summary>
  88. /// <param name="url">接口url</param>
  89. /// <param name="postData"></param>
  90. /// <returns></returns>
  91. public static string Post(string url, object postData)
  92. {
  93. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  94. req.Method = "POST";
  95. req.ContentType = "application/json";
  96. req.Timeout = 3000;
  97. if (req == null)
  98. return string.Empty;
  99. byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(postData));
  100. //注意:无需手动指定长度 (否则可能会报流未处理完就关闭的异常,因为ContentLength时候会比真实post数据长度大)
  101. //req.ContentLength = data.Length;
  102. using (Stream reqStream = req.GetRequestStream())
  103. {
  104. reqStream.Write(data, 0, data.Length);
  105. }
  106. HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  107. if (resp == null)
  108. return string.Empty;
  109. using (Stream stream = resp.GetResponseStream())
  110. {
  111. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  112. {
  113. return reader.ReadToEnd();
  114. }
  115. }
  116. }
  117. /// <summary>
  118. /// Post请求
  119. /// </summary>
  120. /// <param name="url">接口url</param>
  121. /// <param name="dic">参数</param>
  122. /// <returns></returns>
  123. public static string Post(string url, Dictionary<string, string> dic)
  124. {
  125. string result = string.Empty;
  126. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  127. req.Method = "POST";
  128. req.ContentType = "application/x-www-form-urlencoded";
  129. req.Timeout = 3000;
  130. StringBuilder builder = new StringBuilder();
  131. int i = 0;
  132. foreach (var item in dic)
  133. {
  134. if (i > 0)
  135. builder.Append("&");
  136. builder.AppendFormat("{0}={1}", item.Key, item.Value);
  137. i++;
  138. }
  139. byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
  140. req.ContentLength = data.Length;
  141. using (Stream reqStream = req.GetRequestStream())
  142. {
  143. reqStream.Write(data, 0, data.Length);
  144. reqStream.Close();
  145. }
  146. HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  147. Stream stream = resp.GetResponseStream();
  148. //获取响应内容
  149. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  150. {
  151. result = reader.ReadToEnd();
  152. }
  153. return result;
  154. }
  155. /// <summary>
  156. /// Post请求(基于raw)
  157. /// </summary>
  158. /// <param name="url">接口url</param>
  159. /// <param name="json">raw的json参数</param>
  160. /// <returns></returns>
  161. public static async Task<string> Post(string url, string json)
  162. {
  163. using (HttpClient client = new HttpClient())
  164. {
  165. using(var content = new StringContent(json, Encoding.UTF8, "application/json"))
  166. {
  167. using (HttpResponseMessage response = await client.PostAsync(url, content))
  168. {
  169. if (response.IsSuccessStatusCode)
  170. {
  171. string responseContent = await response.Content.ReadAsStringAsync();
  172. return responseContent;
  173. }
  174. else
  175. {
  176. Console.WriteLine("请求失败,状态码:" + response.StatusCode);
  177. return null;
  178. }
  179. }
  180. }
  181. }
  182. }
  183. /// <summary>
  184. /// Post请求
  185. /// </summary>
  186. /// <param name="url"></param>
  187. /// <param name="dic"></param>
  188. /// <param name="headerKey"></param>
  189. /// <param name="headerValue"></param>
  190. /// <returns></returns>
  191. public static string Post(string url, Dictionary<string, string> dic, string headerKey, string headerValue)
  192. {
  193. string result = string.Empty;
  194. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  195. req.Method = "POST";
  196. req.ContentType = "application/x-www-form-urlencoded";
  197. req.Timeout = 3000;
  198. req.Headers[headerKey] = headerValue;
  199. StringBuilder builder = new StringBuilder();
  200. int i = 0;
  201. foreach (var item in dic)
  202. {
  203. if (i > 0)
  204. builder.Append("&");
  205. builder.AppendFormat("{0}={1}", item.Key, item.Value);
  206. i++;
  207. }
  208. byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
  209. req.ContentLength = data.Length;
  210. using (Stream reqStream = req.GetRequestStream())
  211. {
  212. reqStream.Write(data, 0, data.Length);
  213. reqStream.Close();
  214. }
  215. HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  216. Stream stream = resp.GetResponseStream();
  217. //获取响应内容
  218. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  219. {
  220. result = reader.ReadToEnd();
  221. }
  222. return result;
  223. }
  224. #endregion
  225. }

关于 req.ContentType 的赋值,常见用法的有下面这些

  1. /// <summary>
  2. /// HTTP 内容类型(Content-Type)
  3. /// </summary>
  4. public class HttpContentType
  5. {
  6. /// <summary>
  7. /// 资源类型:普通文本
  8. /// </summary>
  9. public const string TEXT_PLAIN = "text/plain";
  10. /// <summary>
  11. /// 资源类型:JSON字符串
  12. /// </summary>
  13. public const string APPLICATION_JSON = "application/json";
  14. /// <summary>
  15. /// 资源类型:未知类型(数据流)
  16. /// </summary>
  17. public const string APPLICATION_OCTET_STREAM = "application/octet-stream";
  18. /// <summary>
  19. /// 资源类型:表单数据(键值对)
  20. /// </summary>
  21. public const string WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";
  22. /// <summary>
  23. /// 资源类型:表单数据(键值对)。编码方式为 gb2312
  24. /// </summary>
  25. public const string WWW_FORM_URLENCODED_GB2312 = "application/x-www-form-urlencoded;charset=gb2312";
  26. /// <summary>
  27. /// 资源类型:表单数据(键值对)。编码方式为 utf-8
  28. /// </summary>
  29. public const string WWW_FORM_URLENCODED_UTF8 = "application/x-www-form-urlencoded;charset=utf-8";
  30. /// <summary>
  31. /// 资源类型:多分部数据
  32. /// </summary>
  33. public const string MULTIPART_FORM_DATA = "multipart/form-data";
  34. }

关于 HttpWebRequest,可以参考微软官方文档

HttpWebRequest 类 (System.Net) | Microsoft Learn

2023.10.17 对上面的版本我又进行了优化,有不足的地方欢迎指出

  1. using Newtonsoft.Json;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Text;
  6. /// <summary>
  7. /// http请求
  8. /// </summary>
  9. public class HttpRequestHelper
  10. {
  11. #region Get
  12. /// <summary>
  13. /// Get请求
  14. /// </summary>
  15. /// <param name="url">请求url</param>
  16. /// <returns></returns>
  17. public static string Get(string url)
  18. {
  19. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  20. req.Method = "GET";
  21. req.Timeout = 3000;
  22. if (req == null) return string.Empty;
  23. using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
  24. using (Stream stream = resp.GetResponseStream())
  25. using (StreamReader reader = new StreamReader(stream))
  26. return reader.ReadToEnd();
  27. }
  28. /// <summary>
  29. /// Get请求
  30. /// </summary>
  31. /// <param name="url"></param>
  32. /// <param name="headerKey"></param>
  33. /// <param name="headerValue"></param>
  34. /// <returns></returns>
  35. public static string Get(string url, string headerKey, string headerValue)
  36. {
  37. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  38. req.Method = "GET";
  39. req.Timeout = 3000;
  40. req.Headers[headerKey] = headerValue;
  41. if (req == null) return string.Empty;
  42. using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
  43. using (Stream stream = resp.GetResponseStream())
  44. using (StreamReader reader = new StreamReader(stream))
  45. return reader.ReadToEnd();
  46. }
  47. #endregion
  48. #region Post
  49. /// <summary>
  50. /// Post请求
  51. /// </summary>
  52. /// <param name="url">接口url</param>
  53. /// <returns></returns>
  54. public static string Post(string url)
  55. {
  56. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  57. req.Method = "POST";
  58. req.Timeout = 3000;
  59. if (req == null) return string.Empty;
  60. using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
  61. using (Stream stream = resp.GetResponseStream())
  62. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  63. return reader.ReadToEnd();
  64. }
  65. /// <summary>
  66. /// Post请求
  67. /// </summary>
  68. /// <param name="url">接口url</param>
  69. /// <param name="postData"></param>
  70. /// <returns></returns>
  71. public static string Post(string url, object postData)
  72. {
  73. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  74. req.Method = "POST";
  75. req.ContentType = "application/json";
  76. req.Timeout = 3000;
  77. if (req == null) return string.Empty;
  78. byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(postData));
  79. using (Stream reqStream = req.GetRequestStream())
  80. reqStream.Write(data, 0, data.Length);
  81. using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
  82. using (Stream stream = resp.GetResponseStream())
  83. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  84. return reader.ReadToEnd();
  85. }
  86. /// <summary>
  87. /// Post请求(基于raw)
  88. /// </summary>
  89. /// <param name="url"></param>
  90. /// <param name="raw"></param>
  91. /// <returns></returns>
  92. public static string Post(string url, string raw)
  93. {
  94. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  95. request.Method = "POST";
  96. request.ContentType = "application/json"; // 设置合适的 Content-Type
  97. request.Timeout = 3000;
  98. if (request == null) return string.Empty;
  99. byte[] requestBodyBytes = Encoding.UTF8.GetBytes(raw);
  100. request.ContentLength = requestBodyBytes.Length;
  101. using (Stream requestStream = request.GetRequestStream())
  102. requestStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
  103. using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
  104. using (Stream responseStream = response.GetResponseStream())
  105. using (StreamReader reader = new StreamReader(responseStream))
  106. return reader.ReadToEnd();
  107. }
  108. /// <summary>
  109. /// Post请求
  110. /// </summary>
  111. /// <param name="url">接口url</param>
  112. /// <param name="dic">参数</param>
  113. /// <returns></returns>
  114. public static string Post(string url, Dictionary<string, string> dic)
  115. {
  116. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  117. req.Method = "POST";
  118. req.ContentType = "application/x-www-form-urlencoded";
  119. req.Timeout = 3000;
  120. StringBuilder builder = new StringBuilder();
  121. int i = 0;
  122. foreach (var item in dic)
  123. {
  124. if (i > 0)
  125. builder.Append("&");
  126. builder.AppendFormat("{0}={1}", item.Key, item.Value);
  127. i++;
  128. }
  129. byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
  130. req.ContentLength = data.Length;
  131. using (Stream reqStream = req.GetRequestStream())
  132. reqStream.Write(data, 0, data.Length);
  133. using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
  134. using (Stream stream = resp.GetResponseStream())
  135. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  136. return reader.ReadToEnd();
  137. }
  138. /// <summary>
  139. /// Post请求
  140. /// </summary>
  141. /// <param name="url"></param>
  142. /// <param name="dic"></param>
  143. /// <param name="headerKey"></param>
  144. /// <param name="headerValue"></param>
  145. /// <returns></returns>
  146. public static string Post(string url, Dictionary<string, string> dic, string headerKey, string headerValue)
  147. {
  148. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  149. req.Method = "POST";
  150. req.ContentType = "application/x-www-form-urlencoded";
  151. req.Timeout = 3000;
  152. req.Headers[headerKey] = headerValue;
  153. StringBuilder builder = new StringBuilder();
  154. int i = 0;
  155. foreach (var item in dic)
  156. {
  157. if (i > 0)
  158. builder.Append("&");
  159. builder.AppendFormat("{0}={1}", item.Key, item.Value);
  160. i++;
  161. }
  162. byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
  163. req.ContentLength = data.Length;
  164. using (Stream reqStream = req.GetRequestStream())
  165. reqStream.Write(data, 0, data.Length);
  166. using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
  167. using (Stream stream = resp.GetResponseStream())
  168. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  169. return reader.ReadToEnd();
  170. }
  171. #endregion
  172. }

下面是异步版的,推荐使用这个版本

类名:HttpClientHelper

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net.Http;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. public class HttpClientHelper
  7. {
  8. #region 字段
  9. private static HttpClient HttpClientWrapper = new HttpClient();
  10. private static int TimeOut = 3;
  11. #endregion
  12. #region Get
  13. /// <summary>
  14. /// Get 请求
  15. /// </summary>
  16. /// <param name="url">链接</param>
  17. /// <returns></returns>
  18. /// <exception cref="TimeoutException"></exception>
  19. /// <exception cref="Exception"></exception>
  20. public static async Task<string> Get(string url)
  21. {
  22. var response = await HttpClientWrapper.GetAsync(url);
  23. response.EnsureSuccessStatusCode();
  24. return await response.Content.ReadAsStringAsync();
  25. }
  26. /// <summary>
  27. /// Get 请求(注意 headerValue 只能单行,不能加入换行符等特殊字符)
  28. /// </summary>
  29. /// <param name="url">链接</param>
  30. /// <param name="headerKey">标题key</param>
  31. /// <param name="headerValue">标题value</param>
  32. /// <returns></returns>
  33. /// <exception cref="TimeoutException"></exception>
  34. /// <exception cref="Exception"></exception>
  35. public static async Task<string> Get(string url, string headerKey, string headerValue)
  36. {
  37. HttpClientWrapper.DefaultRequestHeaders.Clear();
  38. HttpClientWrapper.DefaultRequestHeaders.Add(headerKey, headerValue);
  39. var response = await HttpClientWrapper.GetAsync(url);
  40. response.EnsureSuccessStatusCode();
  41. return await response.Content.ReadAsStringAsync();
  42. }
  43. #endregion
  44. #region Post
  45. /// <summary>
  46. /// Post 请求
  47. /// </summary>
  48. /// <param name="url">链接</param>
  49. /// <param name="content">发送内容</param>
  50. /// <returns></returns>
  51. public static async Task<string> Post(string url, string content)
  52. {
  53. var httpContent = new StringContent(content, Encoding.UTF8, "application/json");
  54. var response = await HttpClientWrapper.PostAsync(url, httpContent);
  55. response.EnsureSuccessStatusCode();
  56. return await response.Content.ReadAsStringAsync();
  57. }
  58. /// <summary>
  59. /// Post 请求(注意 headerValue 只能单行,不能加入换行符等特殊字符)
  60. /// </summary>
  61. /// <param name="url">链接</param>
  62. /// <param name="content">发送内容</param>
  63. /// <param name="headerKey">标题key</param>
  64. /// <param name="headerValue">标题value</param>
  65. /// <returns></returns>
  66. /// <exception cref="TimeoutException"></exception>
  67. /// <exception cref="Exception"></exception>
  68. public static async Task<string> Post(string url, string content, string headerKey, string headerValue)
  69. {
  70. HttpClientWrapper.DefaultRequestHeaders.Clear();
  71. HttpClientWrapper.DefaultRequestHeaders.Add(headerKey, headerValue);
  72. var httpContent = new StringContent(content, Encoding.UTF8, "application/json");
  73. var response = await HttpClientWrapper.PostAsync(url, httpContent);
  74. response.EnsureSuccessStatusCode();
  75. return await response.Content.ReadAsStringAsync();
  76. }
  77. /// <summary>
  78. /// Post 请求(注意 headers 参数只能单行,不能加入换行符等特殊字符)
  79. /// </summary>
  80. /// <param name="url">链接</param>
  81. /// <param name="headers">标题</param>
  82. /// <param name="content">发送内容</param>
  83. /// <returns></returns>
  84. /// <exception cref="TimeoutException"></exception>
  85. /// <exception cref="Exception"></exception>
  86. public static async Task<string> Post(string url, string content, Dictionary<string, string> headers)
  87. {
  88. HttpClientWrapper.DefaultRequestHeaders.Clear();
  89. foreach (var header in headers)
  90. HttpClientWrapper.DefaultRequestHeaders.Add(header.Key, header.Value);
  91. var httpContent = new StringContent(content, Encoding.UTF8, "application/json");
  92. var response = await HttpClientWrapper.PostAsync(url, httpContent);
  93. response.EnsureSuccessStatusCode();
  94. return await response.Content.ReadAsStringAsync();
  95. }
  96. /// <summary>
  97. /// Post 请求(注意 headers 参数只能单行,不能加入换行符等特殊字符)
  98. /// </summary>
  99. /// <param name="url"></param>
  100. /// <param name="parameters">参数合集</param>
  101. /// <param name="headers"></param>
  102. /// <returns></returns>
  103. /// <exception cref="TimeoutException"></exception>
  104. /// <exception cref="Exception"></exception>
  105. public static async Task<string> Post(string url, Dictionary<string, string> parameters, Dictionary<string, string> headers)
  106. {
  107. HttpClientWrapper.DefaultRequestHeaders.Clear();
  108. foreach (var header in headers)
  109. HttpClientWrapper.DefaultRequestHeaders.Add(header.Key, header.Value);
  110. var formContent = new FormUrlEncodedContent(parameters);
  111. var response = await HttpClientWrapper.PostAsync(url, formContent);
  112. response.EnsureSuccessStatusCode();
  113. return await response.Content.ReadAsStringAsync();
  114. }
  115. #endregion
  116. #region 构造函数
  117. static HttpClientHelper()
  118. {
  119. HttpClientWrapper.Timeout = TimeSpan.FromSeconds(TimeOut);
  120. }
  121. private HttpClientHelper() { }
  122. #endregion
  123. }

三、测试

1.Get 请求

在 Program 类中添加下面代码

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace HttpTest
  7. {
  8. internal class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. Test();
  13. Console.ReadKey();
  14. }
  15. static async void Test()
  16. {
  17. string url = "http://localhost:5252/Values";
  18. try
  19. {
  20. string result = await HttpRequestHelper.Get(url);
  21. Console.WriteLine(result);
  22. }
  23. catch (Exception ex)
  24. {
  25. Console.WriteLine("错误:\n{0}", ex.Message);
  26. }
  27. }
  28. }
  29. }

运行:

 将地址故意写错,再次执行,就能捕捉到 “无法连接到服务器” 的错误

2.Post 请求

代码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace HttpTest
  7. {
  8. internal class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. Test();
  13. Console.ReadKey();
  14. }
  15. static async void Test()
  16. {
  17. string url = "http://localhost:5252/Values";
  18. Dictionary<string, string> dic = new Dictionary<string, string>();
  19. dic.Add("json", "你好");
  20. try
  21. {
  22. string result = await HttpRequestHelper.Post(url, dic);
  23. Console.WriteLine(result);
  24. }
  25. catch (Exception ex)
  26. {
  27. Console.WriteLine("错误:\n{0}", ex.Message);
  28. }
  29. }
  30. }
  31. }

运行:

使用 Post 接口需要注意的是,参数的名字必须要和 web api 参数的名字一模一样,比如当前 post 接口的参数名字是 “json”

那么在 dic 添加的键值对,key 也必须是 “json”,如果不是的话,会无法访问到 post 接口

结束

如果这个帖子对你有所帮助,欢迎 关注 + 点赞 + 留言,或者你有疑问的话,也可以私信给我。

end

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/259645?site
推荐阅读
相关标签
  

闽ICP备14008679号