HttpRequestHelper.cs 16 KB

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