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

ZHttpUtil.cs 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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)
  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 (isSt)
  133. {
  134. aesPostData = AesHelper.AesEncrypt(postData, "XINGHUOLIAOYUAN7");
  135. }
  136. AddHeader(webRequest);
  137. byte[] buffer = encoding.GetBytes(aesPostData);
  138. webRequest.ContentLength = buffer.Length;
  139. webRequest.GetRequestStream()
  140. .Write
  141. (
  142. buffer,
  143. 0,
  144. buffer.Length
  145. );
  146. HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
  147. isSt = webResponse.GetResponseHeader("Xh-St") == "true";
  148. responseStream = webResponse.GetResponseStream();
  149. if (responseStream == null) { return ""; }
  150. using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
  151. {
  152. return reader.ReadToEnd();
  153. }
  154. }
  155. catch (Exception)
  156. {
  157. return "";
  158. }
  159. finally
  160. {
  161. if (responseStream != null)
  162. {
  163. responseStream.Dispose();
  164. }
  165. }
  166. }
  167. /// <summary>
  168. /// Post Http请求
  169. /// </summary>
  170. /// <param name="url">请求地址</param>
  171. /// <param name="postData">传输数据</param>
  172. /// <param name="timeout">超时时间</param>
  173. /// <param name="contentType">媒体格式</param>
  174. /// <param name="encode">编码</param>
  175. /// <returns>泛型集合</returns>
  176. public static T PostSignle<T>
  177. (
  178. string url,
  179. int timeout = 5000,
  180. string postData = "",
  181. string contentType = "application/json;",
  182. string encode = "UTF-8"
  183. ) where T : class
  184. {
  185. if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(encode) && !string.IsNullOrEmpty(contentType) && postData != null)
  186. {
  187. try
  188. {
  189. string respstr = PostStr(url, postData);
  190. return JsonHelper.JsonToObj<T>(respstr);
  191. }
  192. catch (Exception)
  193. {
  194. // ignored
  195. }
  196. }
  197. return default;
  198. }
  199. /// <summary>
  200. /// Cookie
  201. /// </summary>
  202. public static CookieContainer cc = new CookieContainer();
  203. /// <summary>
  204. /// Post请求
  205. /// </summary>
  206. /// <param name="serviceaddress">请求地址</param>
  207. /// <param name="contenttype">头 application/x-www-form-urlencoded</param>
  208. /// <param name="strcontent">参数</param>
  209. /// <param name="header">token</param>
  210. /// <param name="timeout"></param>
  211. /// <returns></returns>
  212. public static JObject PostFunction
  213. (
  214. string serviceaddress,
  215. string contenttype,
  216. string strcontent,
  217. string header,
  218. int timeout = 5000
  219. )
  220. {
  221. try
  222. {
  223. string serviceAddress = serviceaddress;
  224. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
  225. WebHeaderCollection myWebHeaderCollection = request.Headers;
  226. request.CookieContainer = cc;
  227. //myWebHeaderCollection.Add("Accept", "*/*");
  228. if (header != "")
  229. {
  230. myWebHeaderCollection.Add("access_token:" + header);
  231. }
  232. request.Timeout = timeout;
  233. request.Method = "POST";
  234. request.ContentType = contenttype;
  235. using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
  236. {
  237. dataStream.Write(strcontent);
  238. dataStream.Close();
  239. }
  240. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  241. string encoding = response.ContentEncoding;
  242. if (encoding.Length < 1)
  243. {
  244. encoding = "UTF-8"; //默认编码
  245. }
  246. // ReSharper disable once AssignNullToNotNullAttribute
  247. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
  248. string retString = reader.ReadToEnd();
  249. retString = retString.Replace("\\r\\n", "");
  250. //解析josn
  251. JObject jo = JObject.Parse(retString);
  252. return jo;
  253. }
  254. catch (Exception ex)
  255. {
  256. LogHelper.WriteErrLog("请求失败(若网络无问题,请重置winsock,解决方法:以管理员方式打开cmd执行 netsh winsock reset 后重启)", ex);
  257. return null;
  258. }
  259. }
  260. /// <summary>
  261. /// HttpWebRequest 下载
  262. /// </summary>
  263. /// <param name="url">URI</param>
  264. /// <param name="filePath"></param>
  265. /// <param name="header"></param>
  266. /// <returns></returns>
  267. public static bool GetDataGetHtml
  268. (
  269. string url,
  270. string filePath,
  271. string header
  272. )
  273. {
  274. try
  275. {
  276. HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
  277. //httpWebRequest.ContentType = "application/x-www-form-urlencoded";
  278. httpWebRequest.Method = "GET";
  279. //httpWebRequest.ContentType = "image/jpeg";
  280. //对发送的数据不使用缓存
  281. httpWebRequest.AllowWriteStreamBuffering = false;
  282. //httpWebRequest.Timeout = 300000;
  283. httpWebRequest.ServicePoint.Expect100Continue = false;
  284. WebHeaderCollection myWebHeaderCollection = httpWebRequest.Headers;
  285. //myWebHeaderCollection.Add("Accept", "*/*");
  286. if (header != "")
  287. {
  288. myWebHeaderCollection.Add("access_token:" + header);
  289. }
  290. HttpWebResponse webRespon = (HttpWebResponse)httpWebRequest.GetResponse();
  291. Stream webStream = webRespon.GetResponseStream();
  292. if (webStream == null)
  293. {
  294. return false;
  295. }
  296. Stream stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
  297. byte[] bArr = new byte[1024];
  298. int size = webStream.Read(bArr, 0, bArr.Length);
  299. while (size > 0)
  300. {
  301. stream.Write(bArr, 0, size);
  302. size = webStream.Read(bArr, 0, bArr.Length);
  303. //M_DownloadInfo.downloadCount = M_DownloadInfo.downloadCount + 1;
  304. }
  305. webRespon.Close();
  306. stream.Close();
  307. webStream.Close();
  308. return true;
  309. }
  310. catch (Exception)
  311. {
  312. return false;
  313. }
  314. }
  315. /// <summary>
  316. /// 上传文件流
  317. /// 创建人:赵耀
  318. /// 创建时间:2020年9月5日
  319. /// </summary>
  320. /// <param name="url">URL</param>
  321. /// <param name="databyte">文件数据流</param>
  322. /// <param name="filename">文件名</param>
  323. /// <param name="formFields">参数 可不传</param>
  324. public static JObject UploadRequestflow(string url, byte[] databyte, string filename, NameValueCollection formFields = null)
  325. {
  326. // 时间戳,用做boundary
  327. string boundary = "-----" + DateTime.Now.Ticks.ToString("x");
  328. byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
  329. //根据uri创建HttpWebRequest对象
  330. HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
  331. httpReq.ContentType = "multipart/form-data; boundary=" + boundary;
  332. httpReq.Method = "POST";
  333. httpReq.KeepAlive = true;
  334. //httpReq.Timeout = 300000;
  335. //httpReq.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存
  336. httpReq.Credentials = CredentialCache.DefaultCredentials;
  337. try
  338. {
  339. Stream postStream = httpReq.GetRequestStream();
  340. //参数
  341. const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
  342. if (formFields != null)
  343. {
  344. foreach (string key in formFields.Keys)
  345. {
  346. postStream.Write
  347. (
  348. boundarybytes,
  349. 0,
  350. boundarybytes.Length
  351. );
  352. string formitem = string.Format
  353. (
  354. formdataTemplate,
  355. key,
  356. formFields[key]
  357. );
  358. byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
  359. postStream.Write
  360. (
  361. formitembytes,
  362. 0,
  363. formitembytes.Length
  364. );
  365. }
  366. }
  367. postStream.Write
  368. (
  369. boundarybytes,
  370. 0,
  371. boundarybytes.Length
  372. );
  373. const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
  374. //文件头
  375. string header = string.Format
  376. (
  377. headerTemplate,
  378. "file",
  379. filename
  380. );
  381. byte[] headerbytes = Encoding.UTF8.GetBytes(header);
  382. postStream.Write
  383. (
  384. headerbytes,
  385. 0,
  386. headerbytes.Length
  387. );
  388. //文件流
  389. postStream.Write
  390. (
  391. databyte,
  392. 0,
  393. databyte.Length
  394. );
  395. //结束边界
  396. byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
  397. postStream.Write
  398. (
  399. boundaryBytes,
  400. 0,
  401. boundaryBytes.Length
  402. );
  403. postStream.Close();
  404. //获取服务器端的响应
  405. JObject jobResult = null;
  406. using (HttpWebResponse response = (HttpWebResponse)httpReq.GetResponse())
  407. {
  408. Stream receiveStream = response.GetResponseStream();
  409. if (receiveStream != null)
  410. {
  411. StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
  412. string returnValue = readStream.ReadToEnd();
  413. jobResult = JObject.Parse(returnValue);
  414. response.Close();
  415. readStream.Close();
  416. }
  417. }
  418. return jobResult;
  419. }
  420. catch (Exception ex)
  421. {
  422. LogHelper.WriteErrLog("【文件上传】" + ex.Message, ex);
  423. return null;
  424. }
  425. }
  426. /// <summary>
  427. /// 获取公网IP和地址,失败则获取局域网IP
  428. /// </summary>
  429. /// <param name="addressIp">IP地址</param>
  430. /// <param name="address">地址</param>
  431. /// <returns></returns>
  432. public static bool GetAddressIp(out string addressIp, out string address)
  433. {
  434. addressIp = "";
  435. address = "";
  436. try
  437. {
  438. //请求搜狐获取公网IP,获取失败后获取局域网IP
  439. WebRequest request = WebRequest.Create("http://pv.sohu.com/cityjson?ie=utf-8");
  440. request.Timeout = 10000;
  441. WebResponse response = request.GetResponse();
  442. Stream resStream = response.GetResponseStream();
  443. if (resStream != null)
  444. {
  445. StreamReader sr = new StreamReader(resStream, System.Text.Encoding.UTF8);
  446. string htmlinfo = sr.ReadToEnd();
  447. string jsonStr = htmlinfo.Substring(htmlinfo.IndexOf("{", StringComparison.Ordinal), htmlinfo.LastIndexOf("}", StringComparison.Ordinal) - htmlinfo.IndexOf("{", StringComparison.Ordinal) + 1);
  448. JObject obj = JObject.Parse(jsonStr);
  449. addressIp = obj["cip"]?.ToString();
  450. address = obj["cname"]?.ToString();
  451. resStream.Close();
  452. sr.Close();
  453. }
  454. return true;
  455. }
  456. catch (Exception)
  457. {
  458. //获取本地局域网IP
  459. foreach (System.Net.IPAddress ipAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
  460. {
  461. if (ipAddress.AddressFamily.ToString() == "InterNetwork")
  462. {
  463. addressIp = ipAddress.ToString();
  464. }
  465. }
  466. return false;
  467. }
  468. }
  469. }
  470. }