星火微课系统客户端
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ZHttpUtil.cs 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. private static bool CheckValidationResult
  20. (
  21. object sender,
  22. X509Certificate certificate,
  23. X509Chain chain,
  24. SslPolicyErrors errors
  25. )
  26. {
  27. return true; //总是接受
  28. }
  29. public static HttpWebRequest GetHttpWebRequest(string url)
  30. {
  31. HttpWebRequest request;
  32. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  33. {
  34. ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
  35. request = WebRequest.Create(url) as HttpWebRequest;
  36. if (request != null)
  37. {
  38. request.ProtocolVersion = HttpVersion.Version10;
  39. }
  40. }
  41. else
  42. {
  43. request = WebRequest.Create(url) as HttpWebRequest;
  44. }
  45. return request;
  46. }
  47. public static WebResponse Download
  48. (
  49. string downloadUrl,
  50. long from,
  51. long to,
  52. string method
  53. )
  54. {
  55. for (int i = 0; i < 10; i++)
  56. {
  57. try
  58. {
  59. HttpWebRequest request = GetHttpWebRequest(downloadUrl);
  60. request.Accept = "text/json,*/*;q=0.5";
  61. request.AutomaticDecompression = DecompressionMethods.GZip;
  62. request.AddRange(from, to);
  63. request.Headers.Add("Accept-Charset", "utf-8;q=0.7,*;q=0.7");
  64. request.Headers.Add("Accept-Encoding", "gzip, deflate, x-gzip, identity; q=0.9");
  65. request.AutomaticDecompression = System.Net.DecompressionMethods.GZip;
  66. request.Timeout = 120000;
  67. request.Method = method;
  68. request.KeepAlive = false;
  69. request.ContentType = "application/json; charset=utf-8";
  70. return request.GetResponse();
  71. }
  72. catch (Exception)
  73. {
  74. Thread.Sleep(100);
  75. }
  76. }
  77. throw new Exception("已断开网络!请检查网络连接后重试下载!");
  78. }
  79. private static void AddHeader(HttpWebRequest webRequest)
  80. {
  81. webRequest.Headers.Add("Xh-St", isSt ? "true" : "false");
  82. if (!string.IsNullOrEmpty(tokenKey) && !string.IsNullOrEmpty(tokenValue))
  83. {
  84. webRequest.Headers.Add("Xh-Token-Key", tokenKey);
  85. webRequest.Headers.Add("Xh-Token-Value", tokenValue);
  86. }
  87. if (!string.IsNullOrEmpty(userId))
  88. {
  89. webRequest.Headers.Add("Xh-User-Id", userId);
  90. }
  91. webRequest.Headers.Add("Xh-Device", "microlecture_pc_t");
  92. webRequest.Headers.Add("Xh-Version", version);
  93. }
  94. /// <summary>
  95. /// 调用Post接口
  96. /// </summary>
  97. /// <returns></returns>
  98. public static string PostStr
  99. (
  100. string url,
  101. string postData,
  102. bool jm = true,
  103. string contentType = "application/json"
  104. )
  105. {
  106. Stream responseStream = null;
  107. try
  108. {
  109. HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
  110. webRequest.Method = "POST";
  111. webRequest.Accept = "text/html,application/xhtml+xml,*/*";
  112. webRequest.ContentType = contentType + ";" + "UTF-8";
  113. // Console.WriteLine(@"postData:" + postData);
  114. string aesPostData = postData;
  115. if (jm)
  116. {
  117. if (isSt)
  118. {
  119. aesPostData = AesHelper.AesEncrypt(postData, "XINGHUOLIAOYUAN7");
  120. // Console.WriteLine(@"加密再解密后:" + AesHelper.AesDecrypt(aesPostData, "XINGHUOLIAOYUAN7"));
  121. }
  122. AddHeader(webRequest);
  123. }
  124. byte[] buffer = Encoding.UTF8.GetBytes(aesPostData);
  125. webRequest.ContentLength = buffer.Length;
  126. webRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
  127. HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
  128. //只有可能需要加密的接口的响应头才处理
  129. if (jm)
  130. {
  131. isSt = webResponse.GetResponseHeader("Xh-St") == "true";
  132. }
  133. responseStream = webResponse.GetResponseStream();
  134. if (responseStream == null) { return ""; }
  135. using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
  136. {
  137. return reader.ReadToEnd();
  138. }
  139. }
  140. catch (Exception ex)
  141. {
  142. Console.WriteLine(ex.Message);
  143. return "";
  144. }
  145. finally
  146. {
  147. if (responseStream != null)
  148. {
  149. responseStream.Dispose();
  150. }
  151. }
  152. }
  153. /// <summary>
  154. /// Post Http请求
  155. /// </summary>
  156. /// <param name="url">请求地址</param>
  157. /// <param name="postData">传输数据</param>
  158. /// <param name="jm">加密</param>
  159. /// <param name="timeout">超时时间</param>
  160. /// <param name="contentType">媒体格式</param>
  161. /// <param name="encode">编码</param>
  162. /// <returns>泛型集合</returns>
  163. public static T PostSignle<T>
  164. (
  165. string url,
  166. string postData = "",
  167. bool jm = true,
  168. int timeout = 5000,
  169. string contentType = "application/json;",
  170. string encode = "UTF-8"
  171. ) where T : class
  172. {
  173. if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(encode) && !string.IsNullOrEmpty(contentType) && postData != null)
  174. {
  175. try
  176. {
  177. string respstr = PostStr(
  178. url,
  179. postData,
  180. jm,
  181. contentType
  182. );
  183. return JsonHelper.JsonToObj<T>(respstr);
  184. }
  185. catch (Exception ex)
  186. {
  187. Console.WriteLine(ex.ToString());
  188. // ignored
  189. }
  190. }
  191. return default;
  192. }
  193. /// <summary>
  194. /// HttpWebRequest 下载
  195. /// </summary>
  196. /// <param name="url">URI</param>
  197. /// <param name="filePath"></param>
  198. /// <param name="header"></param>
  199. /// <returns></returns>
  200. public static bool DownloadFile(string url, string filePath, string header)
  201. {
  202. try
  203. {
  204. HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
  205. //httpWebRequest.ContentType = "application/x-www-form-urlencoded";
  206. httpWebRequest.Method = "GET";
  207. //httpWebRequest.ContentType = "image/jpeg";
  208. //对发送的数据不使用缓存
  209. httpWebRequest.AllowWriteStreamBuffering = false;
  210. //httpWebRequest.Timeout = 300000;
  211. httpWebRequest.ServicePoint.Expect100Continue = false;
  212. WebHeaderCollection myWebHeaderCollection = httpWebRequest.Headers;
  213. //myWebHeaderCollection.Add("Accept", "*/*");
  214. if (header != "")
  215. {
  216. myWebHeaderCollection.Add("access_token:" + header);
  217. }
  218. HttpWebResponse webRespon = (HttpWebResponse)httpWebRequest.GetResponse();
  219. Stream webStream = webRespon.GetResponseStream();
  220. if (webStream == null)
  221. {
  222. return false;
  223. }
  224. Stream stream = new FileStream(
  225. filePath,
  226. FileMode.Create,
  227. FileAccess.ReadWrite,
  228. FileShare.ReadWrite
  229. );
  230. byte[] bArr = new byte[1024];
  231. int size = webStream.Read(bArr, 0, bArr.Length);
  232. while (size > 0)
  233. {
  234. stream.Write(bArr, 0, size);
  235. size = webStream.Read(bArr, 0, bArr.Length);
  236. //M_DownloadInfo.downloadCount = M_DownloadInfo.downloadCount + 1;
  237. }
  238. webRespon.Close();
  239. stream.Close();
  240. webStream.Close();
  241. return true;
  242. }
  243. catch (Exception)
  244. {
  245. return false;
  246. }
  247. }
  248. /// <summary>
  249. /// 上传文件流
  250. /// 创建人:赵耀
  251. /// 创建时间:2020年9月5日
  252. /// </summary>
  253. /// <param name="url">URL</param>
  254. /// <param name="databyte">文件数据流</param>
  255. /// <param name="filename">文件名</param>
  256. /// <param name="formFields">参数 可不传</param>
  257. public static JObject UploadFile
  258. (
  259. string url,
  260. byte[] databyte,
  261. string filename,
  262. NameValueCollection formFields = null
  263. )
  264. {
  265. // 时间戳,用做boundary
  266. string boundary = "-----" + DateTime.Now.Ticks.ToString("x");
  267. byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
  268. //根据uri创建HttpWebRequest对象
  269. HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
  270. httpReq.ContentType = "multipart/form-data; boundary=" + boundary;
  271. httpReq.Method = "POST";
  272. httpReq.KeepAlive = true;
  273. //httpReq.Timeout = 300000;
  274. //httpReq.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存
  275. httpReq.Credentials = CredentialCache.DefaultCredentials;
  276. try
  277. {
  278. Stream postStream = httpReq.GetRequestStream();
  279. //参数
  280. const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
  281. if (formFields != null)
  282. {
  283. foreach (string key in formFields.Keys)
  284. {
  285. postStream.Write(boundarybytes, 0, boundarybytes.Length);
  286. string formitem = string.Format(formdataTemplate, key, formFields[key]);
  287. byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
  288. postStream.Write(formitembytes, 0, formitembytes.Length);
  289. }
  290. }
  291. postStream.Write(boundarybytes, 0, boundarybytes.Length);
  292. const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
  293. //文件头
  294. string header = string.Format(headerTemplate, "file", filename);
  295. byte[] headerbytes = Encoding.UTF8.GetBytes(header);
  296. postStream.Write(headerbytes, 0, headerbytes.Length);
  297. //文件流
  298. postStream.Write(databyte, 0, databyte.Length);
  299. //结束边界
  300. byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
  301. postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
  302. postStream.Close();
  303. //获取服务器端的响应
  304. JObject jobResult = null;
  305. using (HttpWebResponse response = (HttpWebResponse)httpReq.GetResponse())
  306. {
  307. Stream receiveStream = response.GetResponseStream();
  308. if (receiveStream != null)
  309. {
  310. StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
  311. string returnValue = readStream.ReadToEnd();
  312. jobResult = JObject.Parse(returnValue);
  313. response.Close();
  314. readStream.Close();
  315. }
  316. }
  317. return jobResult;
  318. }
  319. catch (Exception ex)
  320. {
  321. LogHelper.Logerror.Error("【文件上传】" + ex.Message, ex);
  322. return null;
  323. }
  324. }
  325. /// <summary>
  326. /// 获取公网IP和地址,失败则获取局域网IP
  327. /// </summary>
  328. /// <param name="addressIp">IP地址</param>
  329. /// <param name="address">地址</param>
  330. /// <returns></returns>
  331. public static bool GetAddressIp(out string addressIp, out string address)
  332. {
  333. addressIp = "";
  334. address = "";
  335. try
  336. {
  337. //请求搜狐获取公网IP,获取失败后获取局域网IP
  338. WebRequest request = WebRequest.Create("http://pv.sohu.com/cityjson?ie=utf-8");
  339. request.Timeout = 10000;
  340. WebResponse response = request.GetResponse();
  341. Stream resStream = response.GetResponseStream();
  342. if (resStream != null)
  343. {
  344. StreamReader sr = new StreamReader(resStream, System.Text.Encoding.UTF8);
  345. string htmlinfo = sr.ReadToEnd();
  346. string jsonStr = htmlinfo.Substring(htmlinfo.IndexOf("{", StringComparison.Ordinal), htmlinfo.LastIndexOf("}", StringComparison.Ordinal) - htmlinfo.IndexOf("{", StringComparison.Ordinal) + 1);
  347. JObject obj = JObject.Parse(jsonStr);
  348. addressIp = obj["cip"]?.ToString();
  349. address = obj["cname"]?.ToString();
  350. resStream.Close();
  351. sr.Close();
  352. }
  353. return true;
  354. }
  355. catch (Exception)
  356. {
  357. //获取本地局域网IP
  358. foreach (System.Net.IPAddress ipAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
  359. {
  360. if (ipAddress.AddressFamily.ToString() == "InterNetwork")
  361. {
  362. addressIp = ipAddress.ToString();
  363. }
  364. }
  365. return false;
  366. }
  367. }
  368. }
  369. }