HttpHelper.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.IO;
  5. using System.Net;
  6. using System.Net.Cache;
  7. using System.Reflection;
  8. using System.Text;
  9. using IwbZero.ToolCommon.LogHelpers;
  10. using IwbZero.ToolCommon.StringModel;
  11. namespace IwbZero.ToolCommon
  12. {
  13. public static class HttpHelper
  14. {
  15. #region POST
  16. /// <summary>
  17. /// POST请求
  18. /// </summary>
  19. /// <param name="url"></param>
  20. /// <param name="dataStr"></param>
  21. /// <param name="authKey"></param>
  22. /// <param name="callBackUrl"></param>
  23. /// <param name="contentType"></param>
  24. /// <returns></returns>
  25. public static string RequestPost(this string url, string dataStr, string authKey = null, string callBackUrl = "", string contentType = null)
  26. {
  27. ServicePointManager.DefaultConnectionLimit = 512;
  28. string respResult = null;
  29. HttpWebRequest req = null;
  30. try
  31. {
  32. req = GeneratePostWebRequest(url, dataStr, contentType);
  33. if (!string.IsNullOrEmpty(authKey))
  34. {
  35. var base64Str = authKey.EncodeBase64();
  36. SetHeaderValue(req.Headers, "Authorization", "Bearer " + base64Str);
  37. typeof(HttpHelper).LogWarn($"[Authorization]-[{authKey}]-[Bearer {base64Str}]");
  38. }
  39. if (!string.IsNullOrEmpty(callBackUrl))
  40. {
  41. var base64Str = callBackUrl.EncodeBase64();
  42. SetHeaderValue(req.Headers, "CallBackUrl", base64Str);
  43. typeof(HttpHelper).LogWarn($"[CallBackUrl]-[{callBackUrl}]-[ {base64Str}]");
  44. }
  45. respResult = GenerateWebResponse(req);
  46. }
  47. catch (Exception eee)
  48. {
  49. typeof(HttpHelper).LogWarn("[Error]" + eee + eee.Source + eee.StackTrace);
  50. }
  51. finally
  52. {
  53. req?.Abort();
  54. }
  55. return respResult;
  56. }
  57. /// <summary>
  58. /// POST请求
  59. /// </summary>
  60. /// <param name="url"></param>
  61. /// <param name="dataStr"></param>
  62. /// <param name="dicHeader">头部信息字典</param>
  63. /// <param name="contentType"></param>
  64. /// <returns></returns>
  65. public static string RequestPost(this string url, string dataStr, Dictionary<string, string> dicHeader, string contentType = null)
  66. {
  67. ServicePointManager.DefaultConnectionLimit = 512;
  68. string respResult = null;
  69. HttpWebRequest req = null;
  70. try
  71. {
  72. req = GeneratePostWebRequest(url, dataStr, contentType);
  73. if (dicHeader != null)
  74. {
  75. foreach (var dic in dicHeader)
  76. {
  77. if (dic.Value.IsEmpty())
  78. {
  79. continue;
  80. }
  81. var base64Str = dic.Value.EncodeBase64();
  82. if (dic.Key.UAndT() == "AuthKey".UAndT() || dic.Key.UAndT() == "Auth".UAndT() || dic.Key.UAndT() == "Authorization".UAndT())
  83. {
  84. SetHeaderValue(req.Headers, "Authorization", "Bearer " + base64Str);
  85. }
  86. else
  87. {
  88. SetHeaderValue(req.Headers, dic.Key, base64Str);
  89. }
  90. }
  91. }
  92. respResult = GenerateWebResponse(req);
  93. }
  94. catch (Exception eee)
  95. {
  96. typeof(HttpHelper).LogWarn("[Error]" + eee + eee.Source + eee.StackTrace);
  97. }
  98. finally
  99. {
  100. req?.Abort();
  101. }
  102. return respResult;
  103. }
  104. /// <summary>
  105. /// POST请求
  106. /// </summary>
  107. /// <param name="url"></param>
  108. /// <param name="dataStr"></param>
  109. /// <param name="headerFunc">加载头部信息委托</param>
  110. /// <param name="contentType"></param>
  111. /// <returns></returns>
  112. public static string RequestPost(this string url, string dataStr, Func<HttpWebRequest, HttpWebRequest> headerFunc, string contentType = null)
  113. {
  114. ServicePointManager.DefaultConnectionLimit = 512;
  115. string respResult = null;
  116. HttpWebRequest req = null;
  117. try
  118. {
  119. req = GeneratePostWebRequest(url, dataStr, contentType);
  120. req = headerFunc.Invoke(req);
  121. respResult = GenerateWebResponse(req);
  122. }
  123. catch (Exception eee)
  124. {
  125. typeof(HttpHelper).LogWarn("[Error]" + eee + eee.Source + eee.StackTrace);
  126. }
  127. finally
  128. {
  129. req?.Abort();
  130. }
  131. return respResult;
  132. }
  133. #endregion
  134. #region GET
  135. /// <summary>
  136. /// GET请求
  137. /// </summary>
  138. /// <param name="url"></param>
  139. /// <param name="dataStr"></param>
  140. /// <param name="authKey"></param>
  141. /// <param name="callBackUrl"></param>
  142. /// <param name="contentType"></param>
  143. /// <returns></returns>
  144. public static string RequestGet(this string url, string dataStr, string authKey = null, string callBackUrl = "", string contentType = null)
  145. {
  146. ServicePointManager.DefaultConnectionLimit = 512;
  147. string respResult = null;
  148. HttpWebRequest req = null;
  149. try
  150. {
  151. req = GenerateGetWebRequest(url, contentType);
  152. if (!string.IsNullOrEmpty(authKey))
  153. {
  154. var base64Str = authKey.EncodeBase64();
  155. SetHeaderValue(req.Headers, "Authorization", "Bearer " + base64Str);
  156. typeof(HttpHelper).LogWarn($"[Authorization]-[{authKey}]-[Bearer {base64Str}]");
  157. }
  158. if (!string.IsNullOrEmpty(callBackUrl))
  159. {
  160. var base64Str = callBackUrl.EncodeBase64();
  161. SetHeaderValue(req.Headers, "CallBackUrl", base64Str);
  162. typeof(HttpHelper).LogWarn($"[CallBackUrl]-[{callBackUrl}]-[ {base64Str}]");
  163. }
  164. respResult = GenerateWebResponse(req);
  165. }
  166. catch (Exception eee)
  167. {
  168. typeof(HttpHelper).LogWarn("[Error]" + eee + eee.Source + eee.StackTrace);
  169. }
  170. finally
  171. {
  172. req?.Abort();
  173. }
  174. return respResult;
  175. }
  176. /// <summary>
  177. /// GET请求
  178. /// </summary>
  179. /// <param name="url"></param>
  180. /// <param name="dataStr"></param>
  181. /// <param name="dicHeader">头部信息字典</param>
  182. /// <param name="contentType"></param>
  183. /// <returns></returns>
  184. public static string RequestGet(this string url, string dataStr, Dictionary<string, string> dicHeader, string contentType = null)
  185. {
  186. ServicePointManager.DefaultConnectionLimit = 512;
  187. string respResult = null;
  188. HttpWebRequest req = null;
  189. try
  190. {
  191. req = GenerateGetWebRequest(url, contentType);
  192. if (dicHeader != null)
  193. {
  194. foreach (var dic in dicHeader)
  195. {
  196. if (dic.Value.IsEmpty())
  197. {
  198. continue;
  199. }
  200. var base64Str = dic.Value.EncodeBase64();
  201. if (dic.Key.UAndT() == "AuthKey".UAndT() || dic.Key.UAndT() == "Auth".UAndT() || dic.Key.UAndT() == "Authorization".UAndT())
  202. {
  203. SetHeaderValue(req.Headers, "Authorization", "Bearer " + base64Str);
  204. }
  205. else
  206. {
  207. SetHeaderValue(req.Headers, dic.Key, base64Str);
  208. }
  209. }
  210. }
  211. respResult = GenerateWebResponse(req);
  212. }
  213. catch (Exception eee)
  214. {
  215. typeof(HttpHelper).LogWarn("[Error]" + eee + eee.Source + eee.StackTrace);
  216. }
  217. finally
  218. {
  219. req?.Abort();
  220. }
  221. return respResult;
  222. }
  223. /// <summary>
  224. /// GET请求
  225. /// </summary>
  226. /// <param name="url"></param>
  227. /// <param name="dataStr"></param>
  228. /// <param name="headerFunc">加载头部信息委托</param>
  229. /// <param name="contentType"></param>
  230. /// <returns></returns>
  231. public static string RequestGet(this string url, string dataStr, Func<HttpWebRequest, HttpWebRequest> headerFunc, string contentType = null)
  232. {
  233. ServicePointManager.DefaultConnectionLimit = 512;
  234. string respResult = null;
  235. HttpWebRequest req = null;
  236. try
  237. {
  238. req = GenerateGetWebRequest(url, contentType);
  239. req = headerFunc.Invoke(req);
  240. respResult = GenerateWebResponse(req);
  241. }
  242. catch (Exception eee)
  243. {
  244. typeof(HttpHelper).LogWarn("[Error]" + eee + eee.Source + eee.StackTrace);
  245. }
  246. finally
  247. {
  248. req?.Abort();
  249. }
  250. return respResult;
  251. }
  252. #endregion
  253. /// <summary>
  254. /// 设置头部信息
  255. /// </summary>
  256. /// <param name="header"></param>
  257. /// <param name="name"></param>
  258. /// <param name="value"></param>
  259. public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
  260. {
  261. var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic);
  262. if (property != null)
  263. {
  264. if (property.GetValue(header, null) is NameValueCollection collection)
  265. collection[name] = value;
  266. }
  267. }
  268. #region 私有方法
  269. /// <summary>
  270. /// 创建POST请求
  271. /// </summary>
  272. /// <param name="url"></param>
  273. /// <param name="dataStr"></param>
  274. /// <param name="contentType"></param>
  275. /// <returns></returns>
  276. private static HttpWebRequest GeneratePostWebRequest(string url, string dataStr, string contentType = null)
  277. {
  278. typeof(HttpHelper).LogWarn($"[POST]-[{url}]-[{dataStr}]");
  279. GC.Collect();
  280. Uri uri = new Uri(url);
  281. ServicePoint spSite = ServicePointManager.FindServicePoint(uri);
  282. spSite.ConnectionLimit = 50;
  283. var req = (HttpWebRequest)WebRequest.Create(url);
  284. req.Method = "POST";
  285. req.ContentType = contentType ?? "application/json";
  286. req.Accept = "*/*";
  287. req.Timeout = 5 * 60 * 60 * 1000;
  288. req.UserAgent = "Mozilla-Firefox";
  289. //这个在Post的时候,一定要加上,如果服务器返回错误,他还会继续再去请求,不会使用之前的错误数据,做返回数据
  290. req.ServicePoint.Expect100Continue = false;
  291. HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
  292. req.CachePolicy = noCachePolicy;
  293. RequestWriteData(ref req, dataStr);
  294. return req;
  295. }
  296. /// <summary>
  297. /// 创建GET请求
  298. /// </summary>
  299. /// <param name="url"></param>
  300. /// <param name="contentType"></param>
  301. /// <returns></returns>
  302. private static HttpWebRequest GenerateGetWebRequest(string url, string contentType = null)
  303. {
  304. GC.Collect();
  305. Uri uri = new Uri(url);
  306. ServicePoint spSite = ServicePointManager.FindServicePoint(uri);
  307. spSite.ConnectionLimit = 50;
  308. var req = (HttpWebRequest)WebRequest.Create(url);
  309. req.Method = "POST";
  310. req.ContentType = contentType ?? "application/json";
  311. req.Accept = "*/*";
  312. req.Timeout = 5 * 60 * 60 * 1000;
  313. req.UserAgent = "Mozilla-Firefox";
  314. //这个在Post的时候,一定要加上,如果服务器返回错误,他还会继续再去请求,不会使用之前的错误数据,做返回数据
  315. req.ServicePoint.Expect100Continue = false;
  316. HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
  317. req.CachePolicy = noCachePolicy;
  318. return req;
  319. }
  320. /// <summary>
  321. /// 请求加载数据
  322. /// </summary>
  323. /// <param name="req"></param>
  324. /// <param name="dataStr"></param>
  325. private static void RequestWriteData(ref HttpWebRequest req, string dataStr)
  326. {
  327. Stream streamSend = null;
  328. try
  329. {
  330. if (dataStr.IsNotEmpty())
  331. {
  332. byte[] data = Encoding.UTF8.GetBytes(dataStr);
  333. req.ContentLength = data.Length;
  334. streamSend = req.GetRequestStream();
  335. streamSend.Write(data, 0, data.Length);
  336. streamSend.Close();
  337. }
  338. else
  339. {
  340. req.ContentLength = 0;
  341. }
  342. }
  343. catch (WebException wex)
  344. {
  345. typeof(HttpHelper).LogWarn("[Error]-[WebException]-" + wex + ",wex.Status=" + wex.Status);
  346. //return null;
  347. }
  348. catch (Exception ex)
  349. {
  350. typeof(HttpHelper).LogWarn("[Error]-[GetRequestStream]-" + ex);
  351. //return null;
  352. }
  353. finally
  354. {
  355. streamSend?.Close();
  356. }
  357. //return req;
  358. }
  359. /// <summary>
  360. /// 响应解析
  361. /// </summary>
  362. /// <param name="req"></param>
  363. /// <returns></returns>
  364. private static string GenerateWebResponse(HttpWebRequest req)
  365. {
  366. string respResult = "";
  367. try
  368. {
  369. WebResponse rsp = req.GetResponse() as HttpWebResponse;
  370. respResult = GetResponseStr(rsp);
  371. typeof(HttpHelper).LogWarn($"End- WITH:[{respResult}]");
  372. }
  373. catch (WebException webEx)
  374. {
  375. respResult = GetResponseStr(webEx.Response);
  376. typeof(HttpHelper).LogWarn($"End- WITH:[{respResult}]");
  377. return respResult;
  378. }
  379. catch (Exception ex)
  380. {
  381. typeof(HttpHelper).LogWarn("[Error]-[SendRequest]-" + ex);
  382. return respResult;
  383. }
  384. return respResult;
  385. }
  386. /// <summary>
  387. /// 读取响应字符串
  388. /// </summary>
  389. /// <param name="rsp"></param>
  390. /// <returns></returns>
  391. private static string GetResponseStr(WebResponse rsp)
  392. {
  393. Stream streamRequest = null;
  394. try
  395. {
  396. string respResult = "";
  397. streamRequest = rsp?.GetResponseStream();
  398. if (streamRequest != null)
  399. using (StreamReader reader = new StreamReader(streamRequest))
  400. {
  401. respResult = reader.ReadToEnd();
  402. }
  403. return respResult;
  404. }
  405. finally
  406. {
  407. streamRequest?.Close();
  408. }
  409. }
  410. #endregion
  411. //public static string SendRequest(this string url, string dataStr, string callBackUrl = "", string authKey = null, string contentType = null)
  412. //{
  413. // ServicePointManager.DefaultConnectionLimit = 512;
  414. // string respResult = null;
  415. // HttpWebRequest req = null;
  416. // typeof(HttpHelper).LogWarn($"Start-[{url}-Back:{callBackUrl}] WITH:[{dataStr}]");
  417. // try
  418. // {
  419. // GC.Collect();
  420. // Uri uri = new Uri(url);
  421. // ServicePoint spSite = ServicePointManager.FindServicePoint(uri);
  422. // spSite.ConnectionLimit = 50;
  423. // Stream streamSend = null;
  424. // req = (HttpWebRequest)WebRequest.Create(url);
  425. // req.Method = "POST";
  426. // if (!string.IsNullOrEmpty(authKey))
  427. // {
  428. // var base64Str = authKey.EncodeBase64();
  429. // SetHeaderValue(req.Headers, "Authorization", "Bearer " + base64Str);
  430. // typeof(HttpHelper).LogWarn($"[Authorization]-[{authKey}]-[Bearer {base64Str}]");
  431. // }
  432. // if (!string.IsNullOrEmpty(callBackUrl))
  433. // {
  434. // var base64Str = callBackUrl.EncodeBase64();
  435. // SetHeaderValue(req.Headers, "CallBackUrl", base64Str);
  436. // typeof(HttpHelper).LogWarn($"[Authorization]-[{authKey}]-[Bearer {base64Str}]");
  437. // }
  438. // req.ContentType = contentType ?? "application/json";
  439. // req.Accept = "*/*";
  440. // req.Timeout = 5 * 60 * 60 * 1000;
  441. // req.UserAgent = "Mozilla-Firefox";
  442. // //这个在Post的时候,一定要加上,如果服务器返回错误,他还会继续再去请求,不会使用之前的错误数据,做返回数据
  443. // req.ServicePoint.Expect100Continue = false;
  444. // HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
  445. // req.CachePolicy = noCachePolicy;
  446. // try
  447. // {
  448. // byte[] data = Encoding.UTF8.GetBytes(dataStr);
  449. // req.ContentLength = data.Length;
  450. // streamSend = req.GetRequestStream();
  451. // streamSend.Write(data, 0, data.Length);
  452. // streamSend.Close();
  453. // }
  454. // catch (WebException wex)
  455. // {
  456. // typeof(HttpHelper).LogWarn("[Error]-[WebException]-" + wex + ",wex.Status=" + wex.Status);
  457. // streamSend?.Close();
  458. // return null;
  459. // }
  460. // catch (Exception ex)
  461. // {
  462. // typeof(HttpHelper).LogWarn("[Error]-[GetRequestStream]-" + ex);
  463. // streamSend?.Close();
  464. // return null;
  465. // }
  466. // finally
  467. // {
  468. // streamSend.Close();
  469. // }
  470. // try
  471. // {
  472. // respResult = GenerateWebResponse(req);
  473. // typeof(HttpHelper).LogWarn($"End- WITH:[{respResult}]");
  474. // }
  475. // catch (WebException httpwex)
  476. // {
  477. // //typeof(HttpRequestHelper).LogWarn("[Error]-[WebException]-" + httpwex + ",wex.Status=" + httpwex.Status);
  478. // respResult = GetResponseStr(httpwex.Response);
  479. // typeof(HttpHelper).LogWarn($"End- WITH:[{respResult}]");
  480. // return respResult;
  481. // }
  482. // catch (Exception httpex)
  483. // {
  484. // typeof(HttpHelper).LogWarn("[Error]-[SendRequest]-" + httpex);
  485. // return respResult;
  486. // }
  487. // }
  488. // catch (Exception eee)
  489. // {
  490. // typeof(HttpHelper).LogWarn("[Error]" + eee + eee.Source + eee.StackTrace);
  491. // }
  492. // finally
  493. // {
  494. // req?.Abort();
  495. // }
  496. // return respResult;
  497. //}
  498. ///// <summary>
  499. ///// Http Get Request
  500. ///// </summary>
  501. ///// <param name="url"></param>
  502. ///// <returns></returns>
  503. //public static string HttpGet(this string url)
  504. //{
  505. // string strGetResponse;
  506. // try
  507. // {
  508. // var getRequest = CreateHttpRequest(url, "GET");
  509. // var getResponse = getRequest.GetResponse() as HttpWebResponse;
  510. // strGetResponse = GetHttpResponse(getResponse, "GET");
  511. // }
  512. // catch (Exception ex)
  513. // {
  514. // strGetResponse = ex.Message;
  515. // }
  516. // return strGetResponse;
  517. //}
  518. ///// <summary>
  519. ///// Http Get Request Async
  520. ///// </summary>
  521. ///// <param name="url"></param>
  522. //public static async void HttpGetAsync(this string url)
  523. //{
  524. // string strGetResponse;
  525. // try
  526. // {
  527. // var getRequest = CreateHttpRequest(url, "GET");
  528. // var getResponse = await getRequest.GetResponseAsync() as HttpWebResponse;
  529. // strGetResponse = GetHttpResponse(getResponse, "GET");
  530. // }
  531. // catch (Exception ex)
  532. // {
  533. // strGetResponse = ex.Message;
  534. // }
  535. // // return strGetResponse;
  536. // Console.WriteLine("reslut:" + strGetResponse);
  537. //}
  538. ///// <summary>
  539. ///// Http Post Request
  540. ///// </summary>
  541. ///// <param name="url"></param>
  542. ///// <param name="postData"></param>
  543. ///// <param name="contentType"></param>
  544. ///// <returns></returns>
  545. //public static string HttpPost(this string url, string postData, string contentType = null)
  546. //{
  547. // int random = new Random().Next(0, 10000);
  548. // typeof(HttpHelper).LogWarn("-->[" + random + "]StartWith : " + url + " [ data:" + postData + "]");
  549. // string strPostReponse;
  550. // HttpWebResponse postResponse = null;
  551. // HttpWebRequest postRequest = null;
  552. // try
  553. // {
  554. // postRequest = CreateHttpRequest(url, "POST", postData, contentType);
  555. // postResponse = postRequest.GetResponse() as HttpWebResponse;
  556. // strPostReponse = GetHttpResponse(postResponse, "POST");
  557. // }
  558. // catch (Exception ex)
  559. // {
  560. // strPostReponse = ex.Message;
  561. // }
  562. // finally
  563. // {
  564. // postRequest?.Abort();
  565. // postResponse?.Close();
  566. // }
  567. // typeof(HttpHelper).LogWarn("-->[" + random + "]EndWith : " + strPostReponse);
  568. // return strPostReponse;
  569. //}
  570. ///// <summary>
  571. ///// Http Post Request Async
  572. ///// </summary>
  573. ///// <param name="url"></param>
  574. ///// <param name="postData"></param>
  575. ///// <param name="contentType"></param>
  576. //public static async Task<string> HttpPostAsync(this string url, string postData, string contentType = null)
  577. //{
  578. // int random = new Random().Next(0, 10000);
  579. // typeof(HttpHelper).LogWarn("-->[" + random + "]StartWith : " + url + " [ data:" + postData + "]");
  580. // string strPostReponse;
  581. // try
  582. // {
  583. // var postRequest = CreatePostHttpWebRequest(url, postData, contentType);
  584. // var postResponse = await postRequest.GetResponseAsync() as HttpWebResponse;
  585. // strPostReponse = GetHttpResponse(postResponse, "POST");
  586. // }
  587. // catch (Exception ex)
  588. // {
  589. // strPostReponse = ex.Message;
  590. // }
  591. // typeof(HttpHelper).LogWarn("-->[" + random + "]EndWith : " + strPostReponse);
  592. // return strPostReponse;
  593. //}
  594. //private static HttpWebRequest CreateHttpRequest(string url, string requestType, params object[] strJson)
  595. //{
  596. // HttpWebRequest request = null;
  597. // const string get = "GET";
  598. // const string post = "POST";
  599. // if (string.Equals(requestType, get, StringComparison.OrdinalIgnoreCase))
  600. // {
  601. // request = CreateGetHttpWebRequest(url);
  602. // }
  603. // if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
  604. // {
  605. // request = CreatePostHttpWebRequest(url, strJson[0].ToString());
  606. // }
  607. // return request;
  608. //}
  609. //private static HttpWebRequest CreateGetHttpWebRequest(string url)
  610. //{
  611. // var getRequest = (HttpWebRequest)WebRequest.Create(url);
  612. // getRequest.Method = "GET";
  613. // getRequest.Timeout = 5000;
  614. // getRequest.ContentType = "text/html;charset=UTF-8";
  615. // getRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
  616. // return getRequest;
  617. //}
  618. //private static HttpWebRequest CreatePostHttpWebRequest(string url, string postData, string contentType = null)
  619. //{
  620. // GC.Collect();
  621. // //ServicePointManager.DefaultConnectionLimit = 10;
  622. // var postRequest = (HttpWebRequest)WebRequest.Create(url);
  623. // postRequest.ServicePoint.Expect100Continue = false;
  624. // postRequest.KeepAlive = false;
  625. // postRequest.Timeout = 5000;
  626. // postRequest.Method = "POST";
  627. // postRequest.ContentType = contentType ?? "application/json";//"application/x-www-form-urlencoded";
  628. // postRequest.AllowWriteStreamBuffering = false;
  629. // byte[] data = Encoding.UTF8.GetBytes(postData);
  630. // postRequest.ContentLength = data.Length;
  631. // Stream newStream = postRequest.GetRequestStream();
  632. // newStream.Write(data, 0, data.Length);
  633. // newStream.Close();
  634. // //StreamWriter writer = new StreamWriter(postRequest.GetRequestStream(), Encoding.ASCII);
  635. // //writer.Write(postData);
  636. // //writer.Flush();
  637. // return postRequest;
  638. //}
  639. //private static string GetHttpResponse(HttpWebResponse response, string requestType)
  640. //{
  641. // const string post = "POST";
  642. // string encoding = "UTF-8";
  643. // if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
  644. // {
  645. // encoding = response.ContentEncoding;
  646. // if (encoding.Length < 1)
  647. // {
  648. // encoding = "UTF-8";
  649. // }
  650. // }
  651. // string responseResult;
  652. // using (StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.GetEncoding(encoding)))
  653. // {
  654. // responseResult = reader.ReadToEnd();
  655. // }
  656. // return responseResult;
  657. //}
  658. ///// <summary>
  659. ///// Base64 编码
  660. ///// </summary>
  661. ///// <param name="encode">编码方式</param>
  662. ///// <param name="source">要编码的字符串</param>
  663. ///// <returns>返回编码后的字符串</returns>
  664. //public static string EncodeBase64(this string source, Encoding encode = null)
  665. //{
  666. // string result;
  667. // try
  668. // {
  669. // encode = encode ?? Encoding.UTF8;
  670. // byte[] bytes = encode.GetBytes(source);
  671. // result = Convert.ToBase64String(bytes);
  672. // }
  673. // catch
  674. // {
  675. // result = source;
  676. // }
  677. // return result;
  678. //}
  679. ///// <summary>
  680. ///// Base64 解码
  681. ///// </summary>
  682. ///// <param name="encode">解码方式</param>
  683. ///// <param name="source">要解码的字符串</param>
  684. ///// <returns>返回解码后的字符串</returns>
  685. //public static string DecodeBase64(this string source, Encoding encode = null)
  686. //{
  687. // string result;
  688. // try
  689. // {
  690. // byte[] bytes = Convert.FromBase64String(source);
  691. // encode = encode ?? Encoding.UTF8;
  692. // result = encode.GetString(bytes);
  693. // }
  694. // catch
  695. // {
  696. // result = source;
  697. // }
  698. // return result;
  699. //}
  700. }
  701. }