HttpRequestHelper.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. using System;
  2. using System.Collections.Specialized;
  3. using System.IO;
  4. using System.Net;
  5. using System.Net.Cache;
  6. using System.Reflection;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace ShwasherSys
  10. {
  11. public static class HttpRequestHelper
  12. {
  13. /// <summary>
  14. /// Http Get Request
  15. /// </summary>
  16. /// <param name="url"></param>
  17. /// <returns></returns>
  18. public static string HttpGet(this string url)
  19. {
  20. string strGetResponse;
  21. try
  22. {
  23. var getRequest = CreateHttpRequest(url, "GET");
  24. var getResponse = getRequest.GetResponse() as HttpWebResponse;
  25. strGetResponse = GetHttpResponse(getResponse, "GET");
  26. }
  27. catch (Exception ex)
  28. {
  29. strGetResponse = ex.Message;
  30. }
  31. return strGetResponse;
  32. }
  33. /// <summary>
  34. /// Http Get Request Async
  35. /// </summary>
  36. /// <param name="url"></param>
  37. public static async void HttpGetAsync(this string url)
  38. {
  39. string strGetResponse;
  40. try
  41. {
  42. var getRequest = CreateHttpRequest(url, "GET");
  43. var getResponse = await getRequest.GetResponseAsync() as HttpWebResponse;
  44. strGetResponse = GetHttpResponse(getResponse, "GET");
  45. }
  46. catch (Exception ex)
  47. {
  48. strGetResponse = ex.Message;
  49. }
  50. // return strGetResponse;
  51. Console.WriteLine("reslut:" + strGetResponse);
  52. }
  53. /// <summary>
  54. /// Http Post Request
  55. /// </summary>
  56. /// <param name="url"></param>
  57. /// <param name="postData"></param>
  58. /// <param name="contentType"></param>
  59. /// <returns></returns>
  60. public static string HttpPost(this string url, string postData, string contentType = null)
  61. {
  62. int random = new Random().Next(0, 10000);
  63. typeof(HttpRequestHelper).LogDebug("-->[" + random + "]StartWith : " + url + " [ data:" + postData + "]");
  64. string strPostReponse;
  65. HttpWebResponse postResponse = null;
  66. HttpWebRequest postRequest = null;
  67. try
  68. {
  69. postRequest = CreateHttpRequest(url, "POST", postData, contentType);
  70. postResponse = postRequest.GetResponse() as HttpWebResponse;
  71. strPostReponse = GetHttpResponse(postResponse, "POST");
  72. }
  73. catch (Exception ex)
  74. {
  75. strPostReponse = ex.Message;
  76. }
  77. finally
  78. {
  79. postRequest?.Abort();
  80. postResponse?.Close();
  81. }
  82. typeof(HttpRequestHelper).LogDebug("-->[" + random + "]EndWith : " + strPostReponse);
  83. return strPostReponse;
  84. }
  85. /// <summary>
  86. /// Http Post Request Async
  87. /// </summary>
  88. /// <param name="url"></param>
  89. /// <param name="postData"></param>
  90. /// <param name="contentType"></param>
  91. public static async Task<string> HttpPostAsync(this string url, string postData, string contentType = null)
  92. {
  93. int random = new Random().Next(0, 10000);
  94. typeof(HttpRequestHelper).LogDebug("-->[" + random + "]StartWith : " + url + " [ data:" + postData + "]");
  95. string strPostReponse;
  96. try
  97. {
  98. var postRequest = CreatePostHttpWebRequest(url, postData, contentType);
  99. var postResponse = await postRequest.GetResponseAsync() as HttpWebResponse;
  100. strPostReponse = GetHttpResponse(postResponse, "POST");
  101. }
  102. catch (Exception ex)
  103. {
  104. strPostReponse = ex.Message;
  105. }
  106. typeof(HttpRequestHelper).LogDebug("-->[" + random + "]EndWith : " + strPostReponse);
  107. return strPostReponse;
  108. }
  109. private static HttpWebRequest CreateHttpRequest(string url, string requestType, params object[] strJson)
  110. {
  111. HttpWebRequest request = null;
  112. const string get = "GET";
  113. const string post = "POST";
  114. if (string.Equals(requestType, get, StringComparison.OrdinalIgnoreCase))
  115. {
  116. request = CreateGetHttpWebRequest(url);
  117. }
  118. if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
  119. {
  120. request = CreatePostHttpWebRequest(url, strJson[0].ToString());
  121. }
  122. return request;
  123. }
  124. private static HttpWebRequest CreateGetHttpWebRequest(string url)
  125. {
  126. var getRequest = (HttpWebRequest)WebRequest.Create(url);
  127. getRequest.Method = "GET";
  128. getRequest.Timeout = 5000;
  129. getRequest.ContentType = "text/html;charset=UTF-8";
  130. getRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
  131. return getRequest;
  132. }
  133. private static HttpWebRequest CreatePostHttpWebRequest(string url, string postData, string contentType = null)
  134. {
  135. GC.Collect();
  136. //ServicePointManager.DefaultConnectionLimit = 10;
  137. var postRequest = (HttpWebRequest)WebRequest.Create(url);
  138. postRequest.ServicePoint.Expect100Continue = false;
  139. postRequest.KeepAlive = false;
  140. postRequest.Timeout = 5000;
  141. postRequest.Method = "POST";
  142. postRequest.ContentType = contentType ?? "application/json";//"application/x-www-form-urlencoded";
  143. postRequest.AllowWriteStreamBuffering = false;
  144. byte[] data = Encoding.UTF8.GetBytes(postData);
  145. postRequest.ContentLength = data.Length;
  146. Stream newStream = postRequest.GetRequestStream();
  147. newStream.Write(data, 0, data.Length);
  148. newStream.Close();
  149. //StreamWriter writer = new StreamWriter(postRequest.GetRequestStream(), Encoding.ASCII);
  150. //writer.Write(postData);
  151. //writer.Flush();
  152. return postRequest;
  153. }
  154. private static string GetHttpResponse(HttpWebResponse response, string requestType)
  155. {
  156. const string post = "POST";
  157. string encoding = "UTF-8";
  158. if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
  159. {
  160. encoding = response.ContentEncoding;
  161. if (encoding.Length < 1)
  162. {
  163. encoding = "UTF-8";
  164. }
  165. }
  166. string responseResult;
  167. using (StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.GetEncoding(encoding)))
  168. {
  169. responseResult = reader.ReadToEnd();
  170. }
  171. return responseResult;
  172. }
  173. public static string SendRequest(this string urlStr, string dataStr, string authKey = null, string contentType = null)
  174. {
  175. ServicePointManager.DefaultConnectionLimit = 512;
  176. string respResult = null;
  177. HttpWebRequest req = null;
  178. typeof(HttpRequestHelper).LogDebug($"Statr-[{urlStr}-{authKey}] WITH:[{dataStr}]");
  179. try
  180. {
  181. GC.Collect();
  182. Uri uri = new Uri(urlStr);
  183. ServicePoint spSite = ServicePointManager.FindServicePoint(uri);
  184. spSite.ConnectionLimit = 50;
  185. Stream streamSend = null;
  186. req = (HttpWebRequest)WebRequest.Create(urlStr);
  187. req.Method = "POST";
  188. if (!string.IsNullOrEmpty(authKey))
  189. {
  190. var base64Str = authKey.EncodeBase64();
  191. SetHeaderValue(req.Headers, "Authorization", "Bearer " + base64Str);
  192. typeof(HttpRequestHelper).LogDebug($"[Authorization]-[{authKey}]-[Bearer {base64Str}]");
  193. }
  194. req.ContentType = contentType ?? "application/json";
  195. req.Accept = "*/*";
  196. req.Timeout = 5 * 60 * 60 * 1000;
  197. req.UserAgent = "Mozilla-Firefox";
  198. //这个在Post的时候,一定要加上,如果服务器返回错误,他还会继续再去请求,不会使用之前的错误数据,做返回数据
  199. req.ServicePoint.Expect100Continue = false;
  200. HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
  201. req.CachePolicy = noCachePolicy;
  202. try
  203. {
  204. byte[] data = Encoding.UTF8.GetBytes(dataStr);
  205. req.ContentLength = data.Length;
  206. streamSend = req.GetRequestStream();
  207. streamSend.Write(data, 0, data.Length);
  208. streamSend.Close();
  209. }
  210. catch (WebException wex)
  211. {
  212. typeof(HttpRequestHelper).LogDebug("[Error]-[WebException]-" + wex + ",wex.Status=" + wex.Status);
  213. streamSend?.Close();
  214. return null;
  215. }
  216. catch (Exception ex)
  217. {
  218. typeof(HttpRequestHelper).LogDebug("[Error]-[GetRequestStream]-" + ex);
  219. streamSend?.Close();
  220. return null;
  221. }
  222. try
  223. {
  224. respResult = GetResp(req);
  225. typeof(HttpRequestHelper).LogDebug($"End- WITH:[{respResult}]");
  226. }
  227. catch (WebException httpwex)
  228. {
  229. //typeof(HttpRequestHelper).LogDebug("[Error]-[WebException]-" + httpwex + ",wex.Status=" + httpwex.Status);
  230. respResult = GetRespStr(httpwex.Response);
  231. typeof(HttpRequestHelper).LogDebug($"End- WITH:[{respResult}]");
  232. return respResult;
  233. }
  234. catch (Exception httpex)
  235. {
  236. typeof(HttpRequestHelper).LogDebug("[Error]-[SendRequest]-" + httpex);
  237. return respResult;
  238. }
  239. finally
  240. {
  241. streamSend.Close();
  242. }
  243. }
  244. catch (Exception eee)
  245. {
  246. typeof(HttpRequestHelper).LogDebug("[Error]" + eee + eee.Source + eee.StackTrace);
  247. }
  248. finally
  249. {
  250. req?.Abort();
  251. req = null;
  252. }
  253. return respResult;
  254. }
  255. public static async Task<string> SendRequestAsync(this string urlStr, string dataStr, string authKey = null, string contentType = null)
  256. {
  257. string respResult = null;
  258. typeof(HttpRequestHelper).LogDebug($"Statr-[{urlStr}-{authKey}] WITH:[{dataStr}]");
  259. try
  260. {
  261. Stream streamSend = null;
  262. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urlStr);
  263. req.Method = "POST";
  264. if (!string.IsNullOrEmpty(authKey))
  265. {
  266. var base64Str = authKey.EncodeBase64();
  267. SetHeaderValue(req.Headers, "Authorization", "Bearer " + base64Str);
  268. }
  269. req.ContentType = contentType ?? "application/json";
  270. req.Accept = "*/*";
  271. req.Timeout = 2000;
  272. req.UserAgent = "Mozilla-Firefox-Spider(Wenanry)";
  273. //这个在Post的时候,一定要加上,如果服务器返回错误,他还会继续再去请求,不会使用之前的错误数据,做返回数据
  274. req.ServicePoint.Expect100Continue = false;
  275. HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
  276. req.CachePolicy = noCachePolicy;
  277. try
  278. {
  279. byte[] data = Encoding.UTF8.GetBytes(dataStr);
  280. req.ContentLength = data.Length;
  281. streamSend = req.GetRequestStream();
  282. streamSend.Write(data, 0, data.Length);
  283. streamSend.Close();
  284. }
  285. catch (WebException wex)
  286. {
  287. typeof(HttpRequestHelper).LogDebug("WebException=" + wex + ",wex.Status=" + wex.Status);
  288. streamSend?.Close();
  289. return null;
  290. }
  291. catch (Exception ex)
  292. {
  293. typeof(HttpRequestHelper).LogDebug("GetRequestStream=" + ex);
  294. streamSend?.Close();
  295. return null;
  296. }
  297. try
  298. {
  299. respResult = await GetRespAsync(req);
  300. typeof(HttpRequestHelper).LogDebug($"End- WITH:[{respResult}]");
  301. }
  302. catch (WebException httpwex)
  303. {
  304. typeof(HttpRequestHelper).LogDebug("WebException=" + httpwex + ",wex.Status=" + httpwex.Status);
  305. streamSend.Close();
  306. return null;
  307. }
  308. catch (Exception httpex)
  309. {
  310. typeof(HttpRequestHelper).LogDebug("SendRequest=" + httpex);
  311. return respResult;
  312. }
  313. }
  314. catch (Exception eee)
  315. {
  316. typeof(HttpRequestHelper).LogDebug("eee=" + eee + eee.Source + eee.StackTrace);
  317. }
  318. return respResult;
  319. }
  320. private static async Task<string> GetRespAsync(HttpWebRequest req)
  321. {
  322. Stream streamRequest = null;
  323. try
  324. {
  325. string respResult = "";
  326. streamRequest = (await req.GetResponseAsync()).GetResponseStream();
  327. if (streamRequest != null)
  328. using (StreamReader reader = new StreamReader(streamRequest))
  329. {
  330. respResult = reader.ReadToEnd();
  331. }
  332. return respResult;
  333. }
  334. finally
  335. {
  336. streamRequest?.Close();
  337. }
  338. }
  339. private static string GetResp(HttpWebRequest req)
  340. {
  341. string respResult = GetRespStr(req.GetResponse());
  342. return respResult;
  343. }
  344. private static string GetRespStr(WebResponse rsp)
  345. {
  346. Stream streamRequest = null;
  347. try
  348. {
  349. string respResult = "";
  350. streamRequest = rsp.GetResponseStream();
  351. if (streamRequest != null)
  352. using (StreamReader reader = new StreamReader(streamRequest))
  353. {
  354. respResult = reader.ReadToEnd();
  355. }
  356. return respResult;
  357. }
  358. finally
  359. {
  360. streamRequest?.Close();
  361. }
  362. }
  363. private static void SetHeaderValue(WebHeaderCollection header, string name, string value)
  364. {
  365. var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic);
  366. if (property != null)
  367. {
  368. if (property.GetValue(header, null) is NameValueCollection collection)
  369. collection[name] = value;
  370. }
  371. }
  372. }
  373. }