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.

576 lines
21 KiB

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