星火微课系统客户端
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.

HttpHelper.cs 23KB

4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Collections.Specialized;
  5. using System.IO;
  6. using System.Net;
  7. using System.Net.Security;
  8. using System.Security.Cryptography.X509Certificates;
  9. using System.Text;
  10. using System.Threading;
  11. namespace Common.system
  12. {
  13. /// <summary>
  14. /// HttpHelper
  15. /// 创建人:赵耀
  16. /// </summary>
  17. public class HttpHelper
  18. {
  19. public static void init_Request(ref System.Net.HttpWebRequest request)
  20. {
  21. request.Accept = "text/json,*/*;q=0.5";
  22. request.Headers.Add("Accept-Charset", "utf-8;q=0.7,*;q=0.7");
  23. request.Headers.Add("Accept-Encoding", "gzip, deflate, x-gzip, identity; q=0.9");
  24. request.AutomaticDecompression = System.Net.DecompressionMethods.GZip;
  25. request.Timeout = 8000;
  26. }
  27. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  28. {
  29. return true; //总是接受
  30. }
  31. public static System.Net.HttpWebRequest GetHttpWebRequest(string url)
  32. {
  33. HttpWebRequest request = null;
  34. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  35. {
  36. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  37. request = WebRequest.Create(url) as HttpWebRequest;
  38. request.ProtocolVersion = HttpVersion.Version10;
  39. }
  40. else
  41. {
  42. request = WebRequest.Create(url) as HttpWebRequest;
  43. }
  44. return request;
  45. }
  46. public static WebResponse Download(string downloadUrl, long from, long to, string method)
  47. {
  48. for (int i = 0; i < 10; i++)
  49. {
  50. try
  51. {
  52. var request = HttpHelper.GetHttpWebRequest(downloadUrl);
  53. HttpHelper.init_Request(ref request);
  54. request.Accept = "text/json,*/*;q=0.5";
  55. request.AddRange(from, to);
  56. request.Headers.Add("Accept-Charset", "utf-8;q=0.7,*;q=0.7");
  57. request.Headers.Add("Accept-Encoding", "gzip, deflate, x-gzip, identity; q=0.9");
  58. request.AutomaticDecompression = System.Net.DecompressionMethods.GZip;
  59. request.Timeout = 120000;
  60. request.Method = method;
  61. request.KeepAlive = false;
  62. request.ContentType = "application/json; charset=utf-8";
  63. return request.GetResponse();
  64. }
  65. catch (Exception)
  66. {
  67. Thread.Sleep(100);
  68. }
  69. }
  70. throw new Exception("已断开网络!请检查网络连接后重试下载!");
  71. }
  72. public static string Get(string url, IDictionary<string, string> param)
  73. {
  74. var paramBuilder = new List<string>();
  75. foreach (var item in param)
  76. {
  77. paramBuilder.Add(string.Format("{0}={1}", item.Key, item.Value));
  78. }
  79. url = string.Format("{0}?{1}", url.TrimEnd('?'), string.Join(",", paramBuilder.ToArray()));
  80. return Get(url);
  81. }
  82. public static string Get(string url)
  83. {
  84. try
  85. {
  86. var request = GetHttpWebRequest(url);
  87. if (request != null)
  88. {
  89. string retval = null;
  90. init_Request(ref request);
  91. using (var Response = request.GetResponse())
  92. {
  93. using (var reader = new System.IO.StreamReader(Response.GetResponseStream(), System.Text.Encoding.UTF8))
  94. {
  95. retval = reader.ReadToEnd();
  96. }
  97. }
  98. return retval;
  99. }
  100. }
  101. catch
  102. {
  103. }
  104. return null;
  105. }
  106. public static string Post(string url, string data)
  107. {
  108. try
  109. {
  110. HttpWebRequest request = GetHttpWebRequest(url);
  111. if (request != null)
  112. {
  113. string retval = null;
  114. init_Request(ref request);
  115. request.Method = "POST";
  116. request.ServicePoint.Expect100Continue = false;
  117. request.ContentType = "application/json; charset=utf-8";
  118. request.Timeout = 5000;
  119. var bytes = System.Text.UTF8Encoding.UTF8.GetBytes(data);
  120. request.ContentLength = bytes.Length;
  121. using (var stream = request.GetRequestStream())
  122. {
  123. stream.Write(bytes, 0, bytes.Length);
  124. }
  125. using (var response = request.GetResponse())
  126. {
  127. using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
  128. {
  129. retval = reader.ReadToEnd();
  130. }
  131. }
  132. return retval;
  133. }
  134. }
  135. catch
  136. {
  137. }
  138. return null;
  139. }
  140. /// <summary>
  141. /// Post Http请求
  142. /// </summary>
  143. /// <param name="url">请求地址</param>
  144. /// <param name="postData">传输数据</param>
  145. /// <param name="timeout">超时时间</param>
  146. /// <param name="contentType">媒体格式</param>
  147. /// <param name="encode">编码</param>
  148. /// <returns>泛型集合</returns>
  149. public static T PostAndRespSignle<T>(string url, int timeout = 5000, string postData = "", string contentType = "application/json;", string encode = "UTF-8") where T : class
  150. {
  151. if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(encode) && !string.IsNullOrEmpty(contentType) && postData != null)
  152. {
  153. // webRequest.Headers.Add("Authorization", "Bearer " + "SportApiAuthData");
  154. HttpWebResponse webResponse = null;
  155. Stream responseStream = null;
  156. Stream requestStream = null;
  157. StreamReader streamReader = null;
  158. try
  159. {
  160. string respstr = GetStreamReader(url, responseStream, requestStream, streamReader, webResponse, timeout, encode, postData, contentType);
  161. return JsonHelper.JsonToObj<T>(respstr);
  162. }
  163. catch (Exception ex)
  164. {
  165. }
  166. finally
  167. {
  168. if (responseStream != null)
  169. {
  170. responseStream.Dispose();
  171. }
  172. if (webResponse != null)
  173. {
  174. webResponse.Close();
  175. }
  176. if (requestStream != null)
  177. {
  178. requestStream.Dispose();
  179. }
  180. if (streamReader != null)
  181. {
  182. streamReader.Dispose();
  183. }
  184. }
  185. }
  186. return default(T);
  187. }
  188. private static string GetStreamReader(string url, Stream responseStream, Stream requestStream, StreamReader streamReader, WebResponse webResponse, int timeout, string encode, string postData, string contentType)
  189. {
  190. try
  191. {
  192. byte[] data = Encoding.GetEncoding(encode).GetBytes(postData);
  193. HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
  194. webRequest.Method = "POST";
  195. webRequest.ContentType = contentType + ";" + encode;
  196. webRequest.ContentLength = data.Length;
  197. webRequest.Timeout = timeout;
  198. requestStream = webRequest.GetRequestStream();
  199. requestStream.Write(data, 0, data.Length);
  200. webResponse = (HttpWebResponse)webRequest.GetResponse();
  201. responseStream = webResponse.GetResponseStream();
  202. if (responseStream == null) { return ""; }
  203. streamReader = new StreamReader(responseStream, Encoding.GetEncoding(encode));
  204. return streamReader.ReadToEnd();
  205. }
  206. catch (Exception ex)
  207. {
  208. return null;
  209. }
  210. }
  211. /// <summary>
  212. /// Cookie
  213. /// </summary>
  214. public static CookieContainer cc = new CookieContainer();
  215. /// <summary>
  216. /// Get请求
  217. /// </summary>
  218. /// <param name="serviceaddress">请求地址</param>
  219. /// <param name="strcontent">头</param>
  220. /// <param name="contenttype">参数</param>
  221. /// <param name="header">token</param>
  222. /// <returns></returns>
  223. public static JObject GetFunction(string serviceaddress, string strcontent, string contenttype, string header, int Timeout = 5000)
  224. {
  225. try
  226. {
  227. string serviceAddress = serviceaddress + strcontent;
  228. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
  229. WebHeaderCollection myWebHeaderCollection = request.Headers;
  230. request.CookieContainer = cc;
  231. if (header != "")
  232. {
  233. myWebHeaderCollection.Add("access_token:" + header);
  234. }
  235. request.Method = "GET";
  236. request.ContentType = contenttype;
  237. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  238. string encoding = response.ContentEncoding;
  239. if (encoding == null || encoding.Length < 1)
  240. {
  241. encoding = "UTF-8"; //默认编码
  242. }
  243. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
  244. string retString = reader.ReadToEnd();
  245. //解析josn
  246. JObject jo = JObject.Parse(retString);
  247. return jo;
  248. }
  249. catch (Exception)
  250. {
  251. return null;
  252. }
  253. }
  254. /// <summary>
  255. /// Post请求
  256. /// </summary>
  257. /// <param name="serviceaddress">请求地址</param>
  258. /// <param name="contenttype">头 application/x-www-form-urlencoded</param>
  259. /// <param name="strcontent">参数</param>
  260. /// <param name="header">token</param>
  261. /// <returns></returns>
  262. public static JObject PostFunction(string serviceaddress, string contenttype, string strcontent, string header, int Timeout = 5000)
  263. {
  264. try
  265. {
  266. string serviceAddress = serviceaddress;
  267. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
  268. WebHeaderCollection myWebHeaderCollection = request.Headers;
  269. request.CookieContainer = cc;
  270. //myWebHeaderCollection.Add("Accept", "*/*");
  271. if (header != "")
  272. {
  273. myWebHeaderCollection.Add("access_token:" + header);
  274. }
  275. request.Timeout = Timeout;
  276. request.Method = "POST";
  277. request.ContentType = contenttype;
  278. string strContent = strcontent;
  279. using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
  280. {
  281. dataStream.Write(strContent);
  282. dataStream.Close();
  283. }
  284. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  285. string encoding = response.ContentEncoding;
  286. if (encoding == null || encoding.Length < 1)
  287. {
  288. encoding = "UTF-8"; //默认编码
  289. }
  290. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
  291. string retString = reader.ReadToEnd();
  292. retString = retString.Replace("\\r\\n", "");
  293. //解析josn
  294. JObject jo = JObject.Parse(retString);
  295. return jo;
  296. }
  297. catch (Exception ex)
  298. {
  299. LogHelper.WriteErrLog("请求失败(若网络无问题,请重置winsock,解决方法:以管理员方式打开cmd执行 netsh winsock reset 后重启)", ex);
  300. return null;
  301. }
  302. }
  303. /// <summary>
  304. /// 上传方法
  305. /// </summary>
  306. /// <param name="url">webapi地址</param>
  307. /// <param name="files">本地文件路径,单文件默认为string[0]</param>
  308. /// <param name="token"></param>
  309. /// <param name="formFields">参数可不传</param>
  310. /// <returns></returns>
  311. public static JObject UploadFilesToRemoteUrl(string url, string[] files, string token, NameValueCollection formFields = null)
  312. {
  313. string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
  314. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  315. request.ContentType = "multipart/form-data; boundary=" +
  316. boundary;
  317. request.Method = "POST";
  318. request.KeepAlive = true;
  319. Stream memStream = new System.IO.MemoryStream();
  320. var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
  321. boundary + "\r\n");
  322. var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
  323. boundary + "--");
  324. WebHeaderCollection myWebHeaderCollection = request.Headers;
  325. request.CookieContainer = cc;
  326. if (token != "")
  327. {
  328. myWebHeaderCollection.Add("access_token:" + token);
  329. }
  330. string formdataTemplate = "\r\n--" + boundary +
  331. "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
  332. if (formFields != null)
  333. {
  334. foreach (string key in formFields.Keys)
  335. {
  336. string formitem = string.Format(formdataTemplate, key, formFields[key]);
  337. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  338. memStream.Write(formitembytes, 0, formitembytes.Length);
  339. }
  340. }
  341. string headerTemplate =
  342. "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
  343. "Content-Type: application/octet-stream\r\n\r\n";
  344. for (int i = 0; i < files.Length; i++)
  345. {
  346. memStream.Write(boundarybytes, 0, boundarybytes.Length);
  347. var header = string.Format(headerTemplate, "file", files[i]);
  348. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  349. memStream.Write(headerbytes, 0, headerbytes.Length);
  350. using (var fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
  351. {
  352. var buffer = new byte[1024];
  353. var bytesRead = 0;
  354. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  355. {
  356. memStream.Write(buffer, 0, bytesRead);
  357. }
  358. }
  359. }
  360. //memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  361. request.ContentLength = memStream.Length;
  362. using (Stream requestStream = request.GetRequestStream())
  363. {
  364. memStream.Position = 0;
  365. byte[] tempBuffer = new byte[memStream.Length];
  366. memStream.Read(tempBuffer, 0, tempBuffer.Length);
  367. memStream.Close();
  368. requestStream.Write(tempBuffer, 0, tempBuffer.Length);
  369. }
  370. using (var response = request.GetResponse())
  371. {
  372. Stream stream2 = response.GetResponseStream();
  373. StreamReader reader2 = new StreamReader(stream2);
  374. JObject a = JObject.Parse(reader2.ReadToEnd());
  375. return a;
  376. }
  377. }
  378. /// <summary>
  379. /// HttpWebRequest 下载
  380. /// </summary>
  381. /// <param name="url">URI</param>
  382. /// <returns></returns>
  383. public static bool GetDataGetHtml(string url, string filePath, string header)
  384. {
  385. try
  386. {
  387. HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
  388. //httpWebRequest.ContentType = "application/x-www-form-urlencoded";
  389. httpWebRequest.Method = "GET";
  390. //httpWebRequest.ContentType = "image/jpeg";
  391. //对发送的数据不使用缓存
  392. httpWebRequest.AllowWriteStreamBuffering = false;
  393. //httpWebRequest.Timeout = 300000;
  394. httpWebRequest.ServicePoint.Expect100Continue = false;
  395. WebHeaderCollection myWebHeaderCollection = httpWebRequest.Headers;
  396. //myWebHeaderCollection.Add("Accept", "*/*");
  397. if (header != "")
  398. {
  399. myWebHeaderCollection.Add("access_token:" + header);
  400. }
  401. HttpWebResponse webRespon = (HttpWebResponse)httpWebRequest.GetResponse();
  402. Stream webStream = webRespon.GetResponseStream();
  403. long length = webRespon.ContentLength;
  404. if (webStream == null)
  405. {
  406. return false;
  407. }
  408. int lengthint = Convert.ToInt32(length);
  409. //int num = lengthint / 1024;
  410. //int count = 0;
  411. //M_DownloadInfo.totalCount = lengthint / 1024;
  412. //M_DownloadInfo.downloadCount = 0;
  413. Stream stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
  414. byte[] bArr = new byte[1024];
  415. int size = webStream.Read(bArr, 0, bArr.Length);
  416. while (size > 0)
  417. {
  418. stream.Write(bArr, 0, size);
  419. size = webStream.Read(bArr, 0, bArr.Length);
  420. //M_DownloadInfo.downloadCount = M_DownloadInfo.downloadCount + 1;
  421. }
  422. webRespon.Close();
  423. stream.Close();
  424. webStream.Close();
  425. return true;
  426. }
  427. catch (Exception ex)
  428. {
  429. //LogHelper.WriteErrLog("请求失败:" + ex.Message, ex);
  430. return false;
  431. }
  432. }
  433. /// <summary>
  434. /// 上传文件流
  435. /// 创建人:赵耀
  436. /// 创建时间:2020年9月5日
  437. /// </summary>
  438. /// <param name="url">URL</param>
  439. /// <param name="databyte">文件数据流</param>
  440. /// <param name="filename">文件名</param>
  441. /// <param name="formFields">参数 可不传</param>
  442. public static JObject UploadRequestflow(string url, byte[] databyte, string filename, NameValueCollection formFields = null)
  443. {
  444. JObject jobResult = null;
  445. // 时间戳,用做boundary
  446. string boundary = "-----" + DateTime.Now.Ticks.ToString("x");
  447. byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
  448. //根据uri创建HttpWebRequest对象
  449. HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
  450. httpReq.ContentType = "multipart/form-data; boundary=" + boundary;
  451. httpReq.Method = "POST";
  452. httpReq.KeepAlive = true;
  453. //httpReq.Timeout = 300000;
  454. //httpReq.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存
  455. httpReq.Credentials = CredentialCache.DefaultCredentials;
  456. try
  457. {
  458. Stream postStream = httpReq.GetRequestStream();
  459. //参数
  460. const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
  461. if (formFields != null)
  462. {
  463. foreach (string key in formFields.Keys)
  464. {
  465. postStream.Write(boundarybytes, 0, boundarybytes.Length);
  466. string formitem = string.Format(formdataTemplate, key, formFields[key]);
  467. byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
  468. postStream.Write(formitembytes, 0, formitembytes.Length);
  469. }
  470. }
  471. postStream.Write(boundarybytes, 0, boundarybytes.Length);
  472. const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
  473. //文件头
  474. string header = string.Format(headerTemplate, "file", filename);
  475. byte[] headerbytes = Encoding.UTF8.GetBytes(header);
  476. postStream.Write(headerbytes, 0, headerbytes.Length);
  477. //文件流
  478. postStream.Write(databyte, 0, databyte.Length);
  479. //结束边界
  480. byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
  481. postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
  482. postStream.Close();
  483. //获取服务器端的响应
  484. using (HttpWebResponse response = (HttpWebResponse)httpReq.GetResponse())
  485. {
  486. Stream receiveStream = response.GetResponseStream();
  487. StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
  488. string returnValue = readStream.ReadToEnd();
  489. jobResult = JObject.Parse(returnValue);
  490. response.Close();
  491. readStream.Close();
  492. //MessageBox.Show(returnValue);
  493. LogHelper.WriteInfoLog("【文件上传】" + returnValue);
  494. }
  495. return jobResult;
  496. }
  497. catch (Exception ex)
  498. {
  499. LogHelper.WriteErrLog("【文件上传】" + ex.Message, ex);
  500. return null;
  501. }
  502. finally
  503. {
  504. httpReq = null;
  505. }
  506. }
  507. }
  508. }