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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. Encoding encoding = Encoding.UTF8;
  110. HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
  111. webRequest.Method = "POST";
  112. webRequest.Accept = "text/html,application/xhtml+xml,*/*";
  113. webRequest.ContentType = contentType + ";" + "UTF-8";
  114. string aesPostData = postData;
  115. if (jm)
  116. {
  117. if (isSt)
  118. {
  119. aesPostData = AesHelper.AesEncrypt(postData, "XINGHUOLIAOYUAN7");
  120. }
  121. AddHeader(webRequest);
  122. }
  123. byte[] buffer = encoding.GetBytes(aesPostData);
  124. webRequest.ContentLength = buffer.Length;
  125. webRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
  126. HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
  127. //只有可能需要加密的接口的响应头才处理
  128. if (jm)
  129. {
  130. isSt = webResponse.GetResponseHeader("Xh-St") == "true";
  131. }
  132. responseStream = webResponse.GetResponseStream();
  133. if (responseStream == null) { return ""; }
  134. using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
  135. {
  136. return reader.ReadToEnd();
  137. }
  138. }
  139. catch (Exception)
  140. {
  141. return "";
  142. }
  143. finally
  144. {
  145. if (responseStream != null)
  146. {
  147. responseStream.Dispose();
  148. }
  149. }
  150. }
  151. /// <summary>
  152. /// Post Http请求
  153. /// </summary>
  154. /// <param name="url">请求地址</param>
  155. /// <param name="postData">传输数据</param>
  156. /// <param name="jm">加密</param>
  157. /// <param name="timeout">超时时间</param>
  158. /// <param name="contentType">媒体格式</param>
  159. /// <param name="encode">编码</param>
  160. /// <returns>泛型集合</returns>
  161. public static T PostSignle<T>
  162. (
  163. string url,
  164. string postData = "",
  165. bool jm = true,
  166. int timeout = 5000,
  167. string contentType = "application/json;",
  168. string encode = "UTF-8"
  169. ) where T : class
  170. {
  171. if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(encode) && !string.IsNullOrEmpty(contentType) && postData != null)
  172. {
  173. try
  174. {
  175. string respstr = PostStr(
  176. url,
  177. postData,
  178. jm,
  179. contentType
  180. );
  181. return JsonHelper.JsonToObj<T>(respstr);
  182. }
  183. catch (Exception)
  184. {
  185. // ignored
  186. }
  187. }
  188. return default;
  189. }
  190. /// <summary>
  191. /// HttpWebRequest 下载
  192. /// </summary>
  193. /// <param name="url">URI</param>
  194. /// <param name="filePath"></param>
  195. /// <param name="header"></param>
  196. /// <returns></returns>
  197. public static bool DownloadFile(string url, string filePath, string header)
  198. {
  199. try
  200. {
  201. HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
  202. //httpWebRequest.ContentType = "application/x-www-form-urlencoded";
  203. httpWebRequest.Method = "GET";
  204. //httpWebRequest.ContentType = "image/jpeg";
  205. //对发送的数据不使用缓存
  206. httpWebRequest.AllowWriteStreamBuffering = false;
  207. //httpWebRequest.Timeout = 300000;
  208. httpWebRequest.ServicePoint.Expect100Continue = false;
  209. WebHeaderCollection myWebHeaderCollection = httpWebRequest.Headers;
  210. //myWebHeaderCollection.Add("Accept", "*/*");
  211. if (header != "")
  212. {
  213. myWebHeaderCollection.Add("access_token:" + header);
  214. }
  215. HttpWebResponse webRespon = (HttpWebResponse)httpWebRequest.GetResponse();
  216. Stream webStream = webRespon.GetResponseStream();
  217. if (webStream == null)
  218. {
  219. return false;
  220. }
  221. Stream stream = new FileStream(
  222. filePath,
  223. FileMode.Create,
  224. FileAccess.ReadWrite,
  225. FileShare.ReadWrite
  226. );
  227. byte[] bArr = new byte[1024];
  228. int size = webStream.Read(bArr, 0, bArr.Length);
  229. while (size > 0)
  230. {
  231. stream.Write(bArr, 0, size);
  232. size = webStream.Read(bArr, 0, bArr.Length);
  233. //M_DownloadInfo.downloadCount = M_DownloadInfo.downloadCount + 1;
  234. }
  235. webRespon.Close();
  236. stream.Close();
  237. webStream.Close();
  238. return true;
  239. }
  240. catch (Exception)
  241. {
  242. return false;
  243. }
  244. }
  245. /// <summary>
  246. /// 上传文件流
  247. /// 创建人:赵耀
  248. /// 创建时间:2020年9月5日
  249. /// </summary>
  250. /// <param name="url">URL</param>
  251. /// <param name="databyte">文件数据流</param>
  252. /// <param name="filename">文件名</param>
  253. /// <param name="formFields">参数 可不传</param>
  254. public static JObject UploadFile
  255. (
  256. string url,
  257. byte[] databyte,
  258. string filename,
  259. NameValueCollection formFields = null
  260. )
  261. {
  262. // 时间戳,用做boundary
  263. string boundary = "-----" + DateTime.Now.Ticks.ToString("x");
  264. byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
  265. //根据uri创建HttpWebRequest对象
  266. HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
  267. httpReq.ContentType = "multipart/form-data; boundary=" + boundary;
  268. httpReq.Method = "POST";
  269. httpReq.KeepAlive = true;
  270. //httpReq.Timeout = 300000;
  271. //httpReq.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存
  272. httpReq.Credentials = CredentialCache.DefaultCredentials;
  273. try
  274. {
  275. Stream postStream = httpReq.GetRequestStream();
  276. //参数
  277. const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
  278. if (formFields != null)
  279. {
  280. foreach (string key in formFields.Keys)
  281. {
  282. postStream.Write(boundarybytes, 0, boundarybytes.Length);
  283. string formitem = string.Format(formdataTemplate, key, formFields[key]);
  284. byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
  285. postStream.Write(formitembytes, 0, formitembytes.Length);
  286. }
  287. }
  288. postStream.Write(boundarybytes, 0, boundarybytes.Length);
  289. const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
  290. //文件头
  291. string header = string.Format(headerTemplate, "file", filename);
  292. byte[] headerbytes = Encoding.UTF8.GetBytes(header);
  293. postStream.Write(headerbytes, 0, headerbytes.Length);
  294. //文件流
  295. postStream.Write(databyte, 0, databyte.Length);
  296. //结束边界
  297. byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
  298. postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
  299. postStream.Close();
  300. //获取服务器端的响应
  301. JObject jobResult = null;
  302. using (HttpWebResponse response = (HttpWebResponse)httpReq.GetResponse())
  303. {
  304. Stream receiveStream = response.GetResponseStream();
  305. if (receiveStream != null)
  306. {
  307. StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
  308. string returnValue = readStream.ReadToEnd();
  309. jobResult = JObject.Parse(returnValue);
  310. response.Close();
  311. readStream.Close();
  312. }
  313. }
  314. return jobResult;
  315. }
  316. catch (Exception ex)
  317. {
  318. LogHelper.Logerror.Error("【文件上传】" + ex.Message, ex);
  319. return null;
  320. }
  321. }
  322. /// <summary>
  323. /// 获取公网IP和地址,失败则获取局域网IP
  324. /// </summary>
  325. /// <param name="addressIp">IP地址</param>
  326. /// <param name="address">地址</param>
  327. /// <returns></returns>
  328. public static bool GetAddressIp(out string addressIp, out string address)
  329. {
  330. addressIp = "";
  331. address = "";
  332. try
  333. {
  334. //请求搜狐获取公网IP,获取失败后获取局域网IP
  335. WebRequest request = WebRequest.Create("http://pv.sohu.com/cityjson?ie=utf-8");
  336. request.Timeout = 10000;
  337. WebResponse response = request.GetResponse();
  338. Stream resStream = response.GetResponseStream();
  339. if (resStream != null)
  340. {
  341. StreamReader sr = new StreamReader(resStream, System.Text.Encoding.UTF8);
  342. string htmlinfo = sr.ReadToEnd();
  343. string jsonStr = htmlinfo.Substring(htmlinfo.IndexOf("{", StringComparison.Ordinal), htmlinfo.LastIndexOf("}", StringComparison.Ordinal) - htmlinfo.IndexOf("{", StringComparison.Ordinal) + 1);
  344. JObject obj = JObject.Parse(jsonStr);
  345. addressIp = obj["cip"]?.ToString();
  346. address = obj["cname"]?.ToString();
  347. resStream.Close();
  348. sr.Close();
  349. }
  350. return true;
  351. }
  352. catch (Exception)
  353. {
  354. //获取本地局域网IP
  355. foreach (System.Net.IPAddress ipAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
  356. {
  357. if (ipAddress.AddressFamily.ToString() == "InterNetwork")
  358. {
  359. addressIp = ipAddress.ToString();
  360. }
  361. }
  362. return false;
  363. }
  364. }
  365. }
  366. }