HttpHelper.cs 28 KB

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