当前位置:   article > 正文

C# 发送POST请求_c# post 请求

c# post 请求
  1. internal static class HttpPost
  2. {
  3. private static string GetBody(Dictionary<string, string> senddata)
  4. {
  5. if (senddata == null)
  6. {
  7. senddata = new Dictionary<string, string>();
  8. }
  9. StringBuilder buffer = new StringBuilder();
  10. int i = 0;
  11. foreach (string k in senddata.Keys)
  12. {
  13. if (i > 0)
  14. {
  15. buffer.AppendFormat("&{0}={1}", k, senddata[k]);
  16. }
  17. else
  18. {
  19. buffer.AppendFormat("{0}={1}", k, senddata[k]);
  20. }
  21. i++;
  22. }
  23. string bodys = buffer.ToString();
  24. return bodys;
  25. }
  26. public static string Send(string url, Dictionary<string, string> headerdata, Dictionary<string, string> senddata)
  27. {
  28. return Send(url, "POST", headerdata, senddata, "application/x-www-form-urlencoded;charset=UTF-8");
  29. }
  30. public static string Send(string url, string method, Dictionary<string, string> headerdata, Dictionary<string, string> senddata)
  31. {
  32. return Send(url, method, headerdata, senddata, "application/x-www-form-urlencoded;charset=UTF-8");
  33. }
  34. public static string Send(string url, string method, Dictionary<string, string> headerdata, Dictionary<string, string> senddata, string contentType)
  35. {
  36. string bodys = GetBody(senddata);
  37. //new internalErrorLog(new Exception(), "SendBody:" + bodys);
  38. HttpWebRequest httpRequest = null;
  39. HttpWebResponse httpResponse = null;
  40. if (url.Contains("https://"))
  41. {
  42. //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  43. /*
  44. 请求某些接口一直返回基础连接已关闭:发送时发生错误
  45. 远程主机强迫关闭了一个现有的连接
  46. */
  47. ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
  48. ServicePointManager.Expect100Continue = false;
  49. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  50. httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
  51. httpRequest.ProtocolVersion = HttpVersion.Version10;
  52. }
  53. else
  54. {
  55. httpRequest = (HttpWebRequest)WebRequest.Create(url);
  56. }
  57. httpRequest.Proxy = null;
  58. httpRequest.Method = method;
  59. foreach (string k in headerdata.Keys)
  60. {
  61. httpRequest.Headers.Add(k, headerdata[k]);
  62. }
  63. //new internalErrorLog(new Exception(), "SendHeader:" + Newtonsoft.Json.JsonConvert.SerializeObject(headerdata));
  64. //根据API的要求,定义相对应的Content-Type
  65. httpRequest.ContentType = contentType;
  66. if (0 < bodys.Length)
  67. {
  68. byte[] data = Encoding.UTF8.GetBytes(bodys);
  69. using (Stream stream = httpRequest.GetRequestStream())
  70. {
  71. stream.Write(data, 0, data.Length);
  72. }
  73. }
  74. try
  75. {
  76. httpRequest.ServicePoint.Expect100Continue = false;
  77. httpResponse = (HttpWebResponse)httpRequest.GetResponse();
  78. Stream st = httpResponse.GetResponseStream();
  79. StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
  80. string json = reader.ReadToEnd();
  81. return json;
  82. }
  83. catch (WebException ex)
  84. {
  85. //new internalErrorLog(ex, "请求URL:" + url);
  86. httpResponse = (HttpWebResponse)ex.Response;
  87. return ex.Message;
  88. }
  89. }
  90. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  91. {
  92. return true;
  93. }
  94. public static string SendGet(string url, Dictionary<string, string> headerdata)
  95. {
  96. HttpWebRequest httpRequest = null;
  97. HttpWebResponse httpResponse = null;
  98. if (url.Contains("https://"))
  99. {
  100. ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
  101. ServicePointManager.Expect100Continue = false;
  102. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  103. httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
  104. httpRequest.ProtocolVersion = HttpVersion.Version10;
  105. }
  106. else
  107. {
  108. httpRequest = (HttpWebRequest)WebRequest.Create(url);
  109. }
  110. httpRequest.Proxy = null;
  111. httpRequest.Method = "Get";
  112. httpRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
  113. foreach (string k in headerdata.Keys)
  114. {
  115. httpRequest.Headers.Add(k, headerdata[k]);
  116. }
  117. try
  118. {
  119. httpResponse = (HttpWebResponse)httpRequest.GetResponse();
  120. Stream st = httpResponse.GetResponseStream();
  121. StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
  122. string json = reader.ReadToEnd();
  123. return json;
  124. }
  125. catch (WebException ex)
  126. {
  127. httpResponse = (HttpWebResponse)ex.Response;
  128. return ex.Message;
  129. }
  130. }
  131. public static string SendJSON(string url, JObject objdata)
  132. {
  133. string jsondata = objdata.ToString();
  134. return SendJSON(url, jsondata);
  135. }
  136. public static string SendJSON(string url, string jsondata)
  137. {
  138. HttpWebRequest httpRequest = null;
  139. HttpWebResponse httpResponse = null;
  140. if (url.Contains("https://"))
  141. {
  142. ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
  143. ServicePointManager.Expect100Continue = false;
  144. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  145. httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
  146. httpRequest.ProtocolVersion = HttpVersion.Version10;
  147. httpRequest.KeepAlive = false;
  148. ServicePointManager.DefaultConnectionLimit = 500;
  149. }
  150. else
  151. {
  152. httpRequest = (HttpWebRequest)WebRequest.Create(url);
  153. }
  154. httpRequest.Proxy = null;
  155. httpRequest.Method = "POST";
  156. httpRequest.ContentType = "application/json";
  157. //WebClient.UploadString("", jsondata);
  158. try
  159. {
  160. httpRequest.ServicePoint.Expect100Continue = false;
  161. byte[] buffer = Encoding.UTF8.GetBytes(jsondata);
  162. //new internalErrorLog(new Exception(jsondata));
  163. httpRequest.ContentLength = buffer.Length;
  164. httpRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
  165. httpResponse = (HttpWebResponse)httpRequest.GetResponse();
  166. Stream st = httpResponse.GetResponseStream();
  167. StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
  168. string json = reader.ReadToEnd();
  169. return json;
  170. }
  171. catch (WebException ex)
  172. {
  173. //new internalErrorLog(ex, "发送地址:" + url);
  174. httpResponse = (HttpWebResponse)ex.Response;
  175. return ex.Message;
  176. }
  177. }
  178. public static string SendJSON(string url, Dictionary<string, string> header, string jsondata)
  179. {
  180. HttpWebRequest httpRequest = null;
  181. HttpWebResponse httpResponse = null;
  182. if (url.Contains("https://"))
  183. {
  184. ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
  185. ServicePointManager.Expect100Continue = false;
  186. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  187. httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
  188. }
  189. else
  190. {
  191. httpRequest = (HttpWebRequest)WebRequest.Create(url);
  192. }
  193. httpRequest.Method = "POST";
  194. httpRequest.ContentType = "application/json";
  195. foreach (string k in header.Keys)
  196. {
  197. httpRequest.Headers.Add(k, header[k]);
  198. }
  199. //WebClient.UploadString("", jsondata);
  200. try
  201. {
  202. httpRequest.ServicePoint.Expect100Continue = false;
  203. byte[] buffer = Encoding.UTF8.GetBytes(jsondata);
  204. //new internalErrorLog(new Exception(jsondata));
  205. httpRequest.ContentLength = buffer.Length;
  206. httpRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
  207. httpResponse = (HttpWebResponse)httpRequest.GetResponse();
  208. Stream st = httpResponse.GetResponseStream();
  209. StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
  210. string json = reader.ReadToEnd();
  211. return json;
  212. }
  213. catch (WebException ex)
  214. {
  215. httpResponse = (HttpWebResponse)ex.Response;
  216. return ex.Message;
  217. }
  218. }
  219. public static string Submit(string url, Hashtable ht, string type)
  220. {
  221. return Submit(url, ht, type, Encoding.Default);
  222. }
  223. public static string Submit(string url, NameValueCollection ht, string type)
  224. {
  225. return Submit(url, ht, type, Encoding.Default);
  226. }
  227. public static string Submit(string url, Hashtable ht, string type, Encoding encoding)
  228. {
  229. IDictionaryEnumerator enumerator = ht.GetEnumerator();
  230. NameValueCollection keyValue = new NameValueCollection();
  231. while (enumerator.MoveNext())
  232. {
  233. keyValue.Add(enumerator.Key.ToString(), (enumerator.Value == null) ? "" : enumerator.Value.ToString());
  234. }
  235. return Submit(url, keyValue, type, encoding);
  236. }
  237. private static string Submit(string url, NameValueCollection keyValue, string type, Encoding encoding)
  238. {
  239. string str = string.Empty;
  240. WebClient client = new WebClient();
  241. try
  242. {
  243. byte[] bytes = client.UploadValues(url, type.ToString(), keyValue);
  244. str = encoding.GetString(bytes);
  245. }
  246. catch (Exception exception)
  247. {
  248. throw exception;
  249. }
  250. finally
  251. {
  252. client.Dispose();
  253. }
  254. return str;
  255. }
  256. }

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/寸_铁/article/detail/748396
推荐阅读
  

闽ICP备14008679号