纽威
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

532 lines
19 KiB

1 year ago
  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. namespace NFine.Code
  11. {
  12. public class HttpMethods
  13. {
  14. #region POST
  15. /// <summary>
  16. /// HTTP POST方式请求数据
  17. /// </summary>
  18. /// <param name="url">URL.</param>
  19. /// <param name="param">POST的数据</param>
  20. /// <returns></returns>
  21. public static string HttpPost(string url, string param = null)
  22. {
  23. HttpWebRequest request;
  24. //如果是发送HTTPS请求
  25. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  26. {
  27. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  28. request = WebRequest.Create(url) as HttpWebRequest;
  29. request.ProtocolVersion = HttpVersion.Version10;
  30. }
  31. else
  32. {
  33. request = WebRequest.Create(url) as HttpWebRequest;
  34. }
  35. request.Method = "POST";
  36. request.ContentType = "application/x-www-form-urlencoded";
  37. request.Accept = "*/*";
  38. request.Timeout = 15000;
  39. request.AllowAutoRedirect = false;
  40. StreamWriter requestStream = null;
  41. WebResponse response = null;
  42. string responseStr = null;
  43. try
  44. {
  45. requestStream = new StreamWriter(request.GetRequestStream());
  46. requestStream.Write(param);
  47. requestStream.Close();
  48. response = request.GetResponse();
  49. if (response != null)
  50. {
  51. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  52. responseStr = reader.ReadToEnd();
  53. reader.Close();
  54. }
  55. }
  56. catch (Exception)
  57. {
  58. throw;
  59. }
  60. finally
  61. {
  62. request = null;
  63. requestStream = null;
  64. response = null;
  65. }
  66. return responseStr;
  67. }
  68. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  69. {
  70. return true; //总是接受
  71. }
  72. public static string BuildRequest(string strUrl, Dictionary<string, string> dicPara, string fileName)
  73. {
  74. string contentType = "image/jpeg";
  75. //待请求参数数组
  76. FileStream Pic = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  77. byte[] PicByte = new byte[Pic.Length];
  78. Pic.Read(PicByte, 0, PicByte.Length);
  79. int lengthFile = PicByte.Length;
  80. //构造请求地址
  81. //设置HttpWebRequest基本信息
  82. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strUrl);
  83. //设置请求方式:get、post
  84. request.Method = "POST";
  85. //设置boundaryValue
  86. string boundaryValue = DateTime.Now.Ticks.ToString("x");
  87. string boundary = "--" + boundaryValue;
  88. request.ContentType = "\r\nmultipart/form-data; boundary=" + boundaryValue;
  89. //设置KeepAlive
  90. request.KeepAlive = true;
  91. //设置请求数据,拼接成字符串
  92. StringBuilder sbHtml = new StringBuilder();
  93. foreach (KeyValuePair<string, string> key in dicPara)
  94. {
  95. sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"" + key.Key + "\"\r\n\r\n" + key.Value + "\r\n");
  96. }
  97. sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"");
  98. sbHtml.Append(fileName);
  99. sbHtml.Append("\"\r\nContent-Type: " + contentType + "\r\n\r\n");
  100. string postHeader = sbHtml.ToString();
  101. //将请求数据字符串类型根据编码格式转换成字节流
  102. Encoding code = Encoding.GetEncoding("UTF-8");
  103. byte[] postHeaderBytes = code.GetBytes(postHeader);
  104. byte[] boundayBytes = Encoding.ASCII.GetBytes("\r\n" + boundary + "--\r\n");
  105. //设置长度
  106. long length = postHeaderBytes.Length + lengthFile + boundayBytes.Length;
  107. request.ContentLength = length;
  108. //请求远程HTTP
  109. Stream requestStream = request.GetRequestStream();
  110. Stream myStream = null;
  111. try
  112. {
  113. //发送数据请求服务器
  114. requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
  115. requestStream.Write(PicByte, 0, lengthFile);
  116. requestStream.Write(boundayBytes, 0, boundayBytes.Length);
  117. HttpWebResponse HttpWResp = (HttpWebResponse)request.GetResponse();
  118. myStream = HttpWResp.GetResponseStream();
  119. }
  120. catch (WebException e)
  121. {
  122. //LogResult(e.Message);
  123. return "";
  124. }
  125. finally
  126. {
  127. if (requestStream != null)
  128. {
  129. requestStream.Close();
  130. }
  131. }
  132. //读取处理结果
  133. StreamReader reader = new StreamReader(myStream, code);
  134. StringBuilder responseData = new StringBuilder();
  135. String line;
  136. while ((line = reader.ReadLine()) != null)
  137. {
  138. responseData.Append(line);
  139. }
  140. myStream.Close();
  141. Pic.Close();
  142. return responseData.ToString();
  143. }
  144. #endregion
  145. #region Put
  146. /// <summary>
  147. /// HTTP Put方式请求数据.
  148. /// </summary>
  149. /// <param name="url">URL.</param>
  150. /// <returns></returns>
  151. public static string HttpPut(string url, string param = null)
  152. {
  153. HttpWebRequest request;
  154. //如果是发送HTTPS请求
  155. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  156. {
  157. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  158. request = WebRequest.Create(url) as HttpWebRequest;
  159. request.ProtocolVersion = HttpVersion.Version10;
  160. }
  161. else
  162. {
  163. request = WebRequest.Create(url) as HttpWebRequest;
  164. }
  165. request.Method = "PUT";
  166. request.ContentType = "application/x-www-form-urlencoded";
  167. request.Accept = "*/*";
  168. request.Timeout = 15000;
  169. request.AllowAutoRedirect = false;
  170. StreamWriter requestStream = null;
  171. WebResponse response = null;
  172. string responseStr = null;
  173. try
  174. {
  175. requestStream = new StreamWriter(request.GetRequestStream());
  176. requestStream.Write(param);
  177. requestStream.Close();
  178. response = request.GetResponse();
  179. if (response != null)
  180. {
  181. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  182. responseStr = reader.ReadToEnd();
  183. reader.Close();
  184. }
  185. }
  186. catch (Exception)
  187. {
  188. throw;
  189. }
  190. finally
  191. {
  192. request = null;
  193. requestStream = null;
  194. response = null;
  195. }
  196. return responseStr;
  197. }
  198. #endregion
  199. #region Delete
  200. /// <summary>
  201. /// HTTP Delete方式请求数据.
  202. /// </summary>
  203. /// <param name="url">URL.</param>
  204. /// <returns></returns>
  205. public static string HttpDelete(string url, string param = null)
  206. {
  207. HttpWebRequest request;
  208. //如果是发送HTTPS请求
  209. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  210. {
  211. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  212. request = WebRequest.Create(url) as HttpWebRequest;
  213. request.ProtocolVersion = HttpVersion.Version10;
  214. }
  215. else
  216. {
  217. request = WebRequest.Create(url) as HttpWebRequest;
  218. }
  219. request.Method = "Delete";
  220. request.ContentType = "application/x-www-form-urlencoded";
  221. request.Accept = "*/*";
  222. request.Timeout = 15000;
  223. request.AllowAutoRedirect = false;
  224. StreamWriter requestStream = null;
  225. WebResponse response = null;
  226. string responseStr = null;
  227. try
  228. {
  229. requestStream = new StreamWriter(request.GetRequestStream());
  230. requestStream.Write(param);
  231. requestStream.Close();
  232. response = request.GetResponse();
  233. if (response != null)
  234. {
  235. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  236. responseStr = reader.ReadToEnd();
  237. reader.Close();
  238. }
  239. }
  240. catch (Exception)
  241. {
  242. throw;
  243. }
  244. return responseStr;
  245. }
  246. #endregion
  247. #region Get
  248. /// <summary>
  249. /// HTTP GET方式请求数据.
  250. /// </summary>
  251. /// <param name="url">URL.</param>
  252. /// <returns></returns>
  253. public static string HttpGet(string url, Hashtable headht = null)
  254. {
  255. HttpWebRequest request;
  256. //如果是发送HTTPS请求
  257. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  258. {
  259. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  260. request = WebRequest.Create(url) as HttpWebRequest;
  261. request.ProtocolVersion = HttpVersion.Version10;
  262. }
  263. else
  264. {
  265. request = WebRequest.Create(url) as HttpWebRequest;
  266. }
  267. request.Method = "GET";
  268. //request.ContentType = "application/x-www-form-urlencoded";
  269. request.Accept = "*/*";
  270. request.Timeout = 15000;
  271. request.AllowAutoRedirect = false;
  272. WebResponse response = null;
  273. string responseStr = null;
  274. if (headht != null)
  275. {
  276. foreach (DictionaryEntry item in headht)
  277. {
  278. request.Headers.Add(item.Key.ToString(), item.Value.ToString());
  279. }
  280. }
  281. try
  282. {
  283. response = request.GetResponse();
  284. if (response != null)
  285. {
  286. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  287. responseStr = reader.ReadToEnd();
  288. reader.Close();
  289. }
  290. }
  291. catch (Exception)
  292. {
  293. throw;
  294. }
  295. return responseStr;
  296. }
  297. public static string HttpGet(string url, Encoding encodeing, Hashtable headht = null)
  298. {
  299. HttpWebRequest request;
  300. //如果是发送HTTPS请求
  301. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  302. {
  303. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  304. request = WebRequest.Create(url) as HttpWebRequest;
  305. request.ProtocolVersion = HttpVersion.Version10;
  306. }
  307. else
  308. {
  309. request = WebRequest.Create(url) as HttpWebRequest;
  310. }
  311. request.Method = "GET";
  312. //request.ContentType = "application/x-www-form-urlencoded";
  313. request.Accept = "*/*";
  314. request.Timeout = 15000;
  315. request.AllowAutoRedirect = false;
  316. WebResponse response = null;
  317. string responseStr = null;
  318. if (headht != null)
  319. {
  320. foreach (DictionaryEntry item in headht)
  321. {
  322. request.Headers.Add(item.Key.ToString(), item.Value.ToString());
  323. }
  324. }
  325. try
  326. {
  327. response = request.GetResponse();
  328. if (response != null)
  329. {
  330. StreamReader reader = new StreamReader(response.GetResponseStream(), encodeing);
  331. responseStr = reader.ReadToEnd();
  332. reader.Close();
  333. }
  334. }
  335. catch (Exception)
  336. {
  337. throw;
  338. }
  339. return responseStr;
  340. }
  341. #endregion
  342. #region Post With Pic
  343. private string HttpPost(string url, IDictionary<object, object> param, string filePath)
  344. {
  345. string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
  346. byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
  347. HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
  348. wr.ContentType = "multipart/form-data; boundary=" + boundary;
  349. wr.Method = "POST";
  350. wr.KeepAlive = true;
  351. wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
  352. Stream rs = wr.GetRequestStream();
  353. string responseStr = null;
  354. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
  355. foreach (string key in param.Keys)
  356. {
  357. rs.Write(boundarybytes, 0, boundarybytes.Length);
  358. string formitem = string.Format(formdataTemplate, key, param[key]);
  359. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  360. rs.Write(formitembytes, 0, formitembytes.Length);
  361. }
  362. rs.Write(boundarybytes, 0, boundarybytes.Length);
  363. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
  364. string header = string.Format(headerTemplate, "pic", filePath, "text/plain");
  365. byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  366. rs.Write(headerbytes, 0, headerbytes.Length);
  367. FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  368. byte[] buffer = new byte[4096];
  369. int bytesRead = 0;
  370. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  371. {
  372. rs.Write(buffer, 0, bytesRead);
  373. }
  374. fileStream.Close();
  375. byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
  376. rs.Write(trailer, 0, trailer.Length);
  377. rs.Close();
  378. WebResponse wresp = null;
  379. try
  380. {
  381. wresp = wr.GetResponse();
  382. Stream stream2 = wresp.GetResponseStream();
  383. StreamReader reader2 = new StreamReader(stream2);
  384. responseStr = reader2.ReadToEnd();
  385. //logger.Debug(string.Format("File uploaded, server response is: {0}", responseStr));
  386. }
  387. catch (Exception ex)
  388. {
  389. //logger.Error("Error uploading file", ex);
  390. if (wresp != null)
  391. {
  392. wresp.Close();
  393. wresp = null;
  394. }
  395. throw;
  396. }
  397. return responseStr;
  398. }
  399. #endregion
  400. #region Post With Pic
  401. /// <summary>
  402. /// HTTP POST方式请求数据(带图片)
  403. /// </summary>
  404. /// <param name="url">URL</param>
  405. /// <param name="param">POST的数据</param>
  406. /// <param name="fileByte">图片</param>
  407. /// <returns></returns>
  408. public static string HttpPost(string url, IDictionary<object, object> param, byte[] fileByte)
  409. {
  410. string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
  411. byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
  412. HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
  413. wr.ContentType = "multipart/form-data; boundary=" + boundary;
  414. wr.Method = "POST";
  415. wr.KeepAlive = true;
  416. wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
  417. Stream rs = wr.GetRequestStream();
  418. string responseStr = null;
  419. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
  420. foreach (string key in param.Keys)
  421. {
  422. rs.Write(boundarybytes, 0, boundarybytes.Length);
  423. string formitem = string.Format(formdataTemplate, key, param[key]);
  424. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  425. rs.Write(formitembytes, 0, formitembytes.Length);
  426. }
  427. rs.Write(boundarybytes, 0, boundarybytes.Length);
  428. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
  429. string header = string.Format(headerTemplate, "pic", fileByte, "text/plain");//image/jpeg
  430. byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  431. rs.Write(headerbytes, 0, headerbytes.Length);
  432. rs.Write(fileByte, 0, fileByte.Length);
  433. byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
  434. rs.Write(trailer, 0, trailer.Length);
  435. rs.Close();
  436. WebResponse wresp = null;
  437. try
  438. {
  439. wresp = wr.GetResponse();
  440. Stream stream2 = wresp.GetResponseStream();
  441. StreamReader reader2 = new StreamReader(stream2);
  442. responseStr = reader2.ReadToEnd();
  443. // logger.Error(string.Format("File uploaded, server response is: {0}", responseStr));
  444. }
  445. catch (Exception ex)
  446. {
  447. //logger.Error("Error uploading file", ex);
  448. if (wresp != null)
  449. {
  450. wresp.Close();
  451. wresp = null;
  452. }
  453. throw;
  454. }
  455. return responseStr;
  456. }
  457. #endregion
  458. #region HttpsClient
  459. /// <summary>
  460. /// 创建HttpClient
  461. /// </summary>
  462. /// <returns></returns>
  463. public static HttpClient CreateHttpClient(string url)
  464. {
  465. HttpClient httpclient;
  466. //如果是发送HTTPS请求
  467. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  468. {
  469. ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
  470. httpclient = new HttpClient();
  471. }
  472. else
  473. {
  474. httpclient = new HttpClient();
  475. }
  476. return httpclient;
  477. }
  478. #endregion
  479. }
  480. }