HttpHelper.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Net;
  6. using System.Net.Http;
  7. using System.Net.Security;
  8. using System.Security.Cryptography.X509Certificates;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace CZFW.Core
  13. {
  14. public static class HttpHelper
  15. {
  16. #region POST
  17. /// <summary>
  18. /// HTTP POST方式请求数据
  19. /// </summary>
  20. /// <param name="url">URL.</param>
  21. /// <param name="param">POST的数据</param>
  22. /// <returns></returns>
  23. public static string HttpPost(string url, string param = null)
  24. {
  25. HttpWebRequest request;
  26. //如果是发送HTTPS请求
  27. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  28. {
  29. ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
  30. request = WebRequest.Create(url) as HttpWebRequest;
  31. request.ProtocolVersion = HttpVersion.Version10;
  32. }
  33. else
  34. {
  35. request = WebRequest.Create(url) as HttpWebRequest;
  36. }
  37. request.Method = "POST";
  38. request.ContentType = "application/x-www-form-urlencoded";
  39. request.Accept = "*/*";
  40. request.Timeout = 15000;
  41. request.AllowAutoRedirect = false;
  42. string responseStr;
  43. var requestStream = new StreamWriter(request.GetRequestStream());
  44. requestStream.Write(param);
  45. requestStream.Close();
  46. var response = request.GetResponse();
  47. {
  48. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  49. responseStr = reader.ReadToEnd();
  50. reader.Close();
  51. }
  52. return responseStr;
  53. }
  54. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  55. {
  56. return true; //总是接受
  57. }
  58. public static string BuildRequest(string strUrl, Dictionary<string, string> dicPara, string fileName)
  59. {
  60. string contentType = "image/jpeg";
  61. //待请求参数数组
  62. FileStream pic = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  63. byte[] picByte = new byte[pic.Length];
  64. pic.Read(picByte, 0, picByte.Length);
  65. int lengthFile = picByte.Length;
  66. //构造请求地址
  67. //设置HttpWebRequest基本信息
  68. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
  69. //设置请求方式:get、post
  70. request.Method = "POST";
  71. //设置boundaryValue
  72. string boundaryValue = DateTime.Now.Ticks.ToString("x");
  73. string boundary = "--" + boundaryValue;
  74. request.ContentType = "\r\nmultipart/form-data; boundary=" + boundaryValue;
  75. //设置KeepAlive
  76. request.KeepAlive = true;
  77. //设置请求数据,拼接成字符串
  78. StringBuilder sbHtml = new StringBuilder();
  79. foreach (KeyValuePair<string, string> key in dicPara)
  80. {
  81. sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"" + key.Key + "\"\r\n\r\n" + key.Value + "\r\n");
  82. }
  83. sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"");
  84. sbHtml.Append(fileName);
  85. sbHtml.Append("\"\r\nContent-Type: " + contentType + "\r\n\r\n");
  86. string postHeader = sbHtml.ToString();
  87. //将请求数据字符串类型根据编码格式转换成字节流
  88. Encoding code = Encoding.GetEncoding("UTF-8");
  89. byte[] postHeaderBytes = code.GetBytes(postHeader);
  90. byte[] boundayBytes = Encoding.ASCII.GetBytes("\r\n" + boundary + "--\r\n");
  91. //设置长度
  92. long length = postHeaderBytes.Length + lengthFile + boundayBytes.Length;
  93. request.ContentLength = length;
  94. //请求远程HTTP
  95. Stream requestStream = request.GetRequestStream();
  96. //发送数据请求服务器
  97. requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
  98. requestStream.Write(picByte, 0, lengthFile);
  99. requestStream.Write(boundayBytes, 0, boundayBytes.Length);
  100. HttpWebResponse httpWResp = (HttpWebResponse)request.GetResponse();
  101. var myStream = httpWResp.GetResponseStream();
  102. //读取处理结果
  103. StreamReader reader = new StreamReader(myStream, code);
  104. StringBuilder responseData = new StringBuilder();
  105. string line;
  106. while ((line = reader.ReadLine()) != null)
  107. {
  108. responseData.Append(line);
  109. }
  110. myStream.Close();
  111. pic.Close();
  112. return responseData.ToString();
  113. }
  114. #endregion
  115. #region Put
  116. /// <summary>
  117. /// HTTP Put方式请求数据.
  118. /// </summary>
  119. /// <param name="url">URL.</param>
  120. /// <param name="param"></param>
  121. /// <returns></returns>
  122. public static string HttpPut(string url, string param = null)
  123. {
  124. HttpWebRequest request;
  125. //如果是发送HTTPS请求
  126. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  127. {
  128. ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
  129. request = WebRequest.Create(url) as HttpWebRequest;
  130. request.ProtocolVersion = HttpVersion.Version10;
  131. }
  132. else
  133. {
  134. request = WebRequest.Create(url) as HttpWebRequest;
  135. }
  136. request.Method = "PUT";
  137. request.ContentType = "application/x-www-form-urlencoded";
  138. request.Accept = "*/*";
  139. request.Timeout = 15000;
  140. request.AllowAutoRedirect = false;
  141. var requestStream = new StreamWriter(request.GetRequestStream());
  142. requestStream.Write(param);
  143. requestStream.Close();
  144. var response = request.GetResponse();
  145. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  146. var responseStr = reader.ReadToEnd();
  147. reader.Close();
  148. return responseStr;
  149. }
  150. #endregion
  151. #region Delete
  152. /// <summary>
  153. /// HTTP Delete方式请求数据.
  154. /// </summary>
  155. /// <param name="url">URL.</param>
  156. /// <param name="param"></param>
  157. /// <returns></returns>
  158. public static string HttpDelete(string url, string param = null)
  159. {
  160. HttpWebRequest request;
  161. //如果是发送HTTPS请求
  162. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  163. {
  164. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  165. request = WebRequest.Create(url) as HttpWebRequest;
  166. request.ProtocolVersion = HttpVersion.Version10;
  167. }
  168. else
  169. {
  170. request = WebRequest.Create(url) as HttpWebRequest;
  171. }
  172. request.Method = "Delete";
  173. request.ContentType = "application/x-www-form-urlencoded";
  174. request.Accept = "*/*";
  175. request.Timeout = 15000;
  176. request.AllowAutoRedirect = false;
  177. string responseStr;
  178. var requestStream = new StreamWriter(request.GetRequestStream());
  179. requestStream.Write(param);
  180. requestStream.Close();
  181. var response = request.GetResponse();
  182. {
  183. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  184. responseStr = reader.ReadToEnd();
  185. reader.Close();
  186. }
  187. return responseStr;
  188. }
  189. #endregion
  190. #region Get
  191. /// <summary>
  192. /// HTTP GET方式请求数据.
  193. /// </summary>
  194. /// <param name="url">URL.</param>
  195. /// <param name="headht"></param>
  196. /// <returns></returns>
  197. public static string HttpGet(string url, Hashtable headht = null)
  198. {
  199. HttpWebRequest request;
  200. //如果是发送HTTPS请求
  201. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  202. {
  203. ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
  204. request = WebRequest.Create(url) as HttpWebRequest;
  205. request.ProtocolVersion = HttpVersion.Version10;
  206. }
  207. else
  208. {
  209. request = WebRequest.Create(url) as HttpWebRequest;
  210. }
  211. request.Method = "GET";
  212. //request.ContentType = "application/x-www-form-urlencoded";
  213. request.Accept = "*/*";
  214. request.Timeout = 15000;
  215. request.AllowAutoRedirect = false;
  216. string responseStr;
  217. if (headht != null)
  218. {
  219. foreach (DictionaryEntry item in headht)
  220. {
  221. request.Headers.Add(item.Key.ToString(), item.Value.ToString());
  222. }
  223. }
  224. var response = request.GetResponse();
  225. {
  226. var test = response.GetResponseStream();
  227. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  228. responseStr = reader.ReadToEnd();
  229. reader.Close();
  230. }
  231. return responseStr;
  232. }
  233. public static string HttpGet(string url, Encoding encodeing, Hashtable headht = null)
  234. {
  235. HttpWebRequest request;
  236. //如果是发送HTTPS请求
  237. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  238. {
  239. ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
  240. request = WebRequest.Create(url) as HttpWebRequest;
  241. request.ProtocolVersion = HttpVersion.Version10;
  242. }
  243. else
  244. {
  245. request = WebRequest.Create(url) as HttpWebRequest;
  246. }
  247. request.Method = "GET";
  248. //request.ContentType = "application/x-www-form-urlencoded";
  249. request.Accept = "*/*";
  250. request.Timeout = 15000;
  251. request.AllowAutoRedirect = false;
  252. string responseStr;
  253. if (headht != null)
  254. {
  255. foreach (DictionaryEntry item in headht)
  256. {
  257. request.Headers.Add(item.Key.ToString(), item.Value.ToString());
  258. }
  259. }
  260. var response = request.GetResponse();
  261. {
  262. StreamReader reader = new StreamReader(response.GetResponseStream(), encodeing);
  263. responseStr = reader.ReadToEnd();
  264. reader.Close();
  265. }
  266. return responseStr;
  267. }
  268. #endregion
  269. #region Post With Pic
  270. /// <summary>
  271. /// HTTP POST方式请求数据(带图片)
  272. /// </summary>
  273. /// <param name="url">URL</param>
  274. /// <param name="param">POST的数据</param>
  275. /// <param name="fileByte">图片</param>
  276. /// <returns></returns>
  277. public static string HttpPost(string url, IDictionary<object, object> param, byte[] fileByte)
  278. {
  279. string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
  280. byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
  281. HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
  282. wr.ContentType = "multipart/form-data; boundary=" + boundary;
  283. wr.Method = "POST";
  284. wr.KeepAlive = true;
  285. wr.Credentials = CredentialCache.DefaultCredentials;
  286. Stream rs = wr.GetRequestStream();
  287. const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
  288. foreach (string key in param.Keys)
  289. {
  290. rs.Write(boundarybytes, 0, boundarybytes.Length);
  291. string formitem = string.Format(formdataTemplate, key, param[key]);
  292. byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
  293. rs.Write(formitembytes, 0, formitembytes.Length);
  294. }
  295. rs.Write(boundarybytes, 0, boundarybytes.Length);
  296. const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
  297. string header = string.Format(headerTemplate, "pic", fileByte, "text/plain");//image/jpeg
  298. byte[] headerbytes = Encoding.UTF8.GetBytes(header);
  299. rs.Write(headerbytes, 0, headerbytes.Length);
  300. rs.Write(fileByte, 0, fileByte.Length);
  301. byte[] trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
  302. rs.Write(trailer, 0, trailer.Length);
  303. rs.Close();
  304. var wresp = wr.GetResponse();
  305. Stream stream2 = wresp.GetResponseStream();
  306. StreamReader reader2 = new StreamReader(stream2);
  307. var responseStr = reader2.ReadToEnd();
  308. return responseStr;
  309. }
  310. #endregion
  311. #region HttpsClient
  312. /// <summary>
  313. /// 创建HttpClient
  314. /// </summary>
  315. /// <returns></returns>
  316. public static HttpClient CreateHttpClient(string url)
  317. {
  318. HttpClient httpclient;
  319. //如果是发送HTTPS请求
  320. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  321. {
  322. ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
  323. httpclient = new HttpClient();
  324. }
  325. else
  326. {
  327. httpclient = new HttpClient();
  328. }
  329. return httpclient;
  330. }
  331. #endregion
  332. public static async Task<string> HttpPost2(string url, string param = null)
  333. {
  334. HttpWebRequest request;
  335. request = WebRequest.Create(url) as HttpWebRequest;
  336. request.Method = "POST";
  337. request.ContentType = "application/json";
  338. request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
  339. request.Timeout = 15000;
  340. request.AllowAutoRedirect = false;
  341. string responseStr;
  342. var requestStream = new StreamWriter(request.GetRequestStream());
  343. requestStream.Write(param);
  344. requestStream.Close();
  345. var response = await request.GetResponseAsync();
  346. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  347. responseStr = reader.ReadToEnd();
  348. reader.Close();
  349. return responseStr;
  350. ;
  351. }
  352. public async static Task<string> HttpPostAsync(string url, string param = null)
  353. {
  354. HttpWebRequest request;
  355. request = WebRequest.Create(url) as HttpWebRequest;
  356. request.Method = "POST";
  357. request.ContentType = "application/x-www-form-urlencoded";
  358. request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
  359. request.Timeout = 15000;
  360. request.AllowAutoRedirect = false;
  361. string responseStr;
  362. var requestStream = new StreamWriter(request.GetRequestStream());
  363. requestStream.Write(param);
  364. requestStream.Close();
  365. var response = await request.GetResponseAsync();
  366. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  367. responseStr = await reader.ReadToEndAsync();
  368. reader.Close();
  369. return responseStr;
  370. }
  371. }
  372. }