星火微课系统客户端
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ZHttpUtil.cs 19KB

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