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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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. using XHWK.WKTool.system;
  14. /// <summary>
  15. /// HttpHelper
  16. /// 创建人:赵耀
  17. /// </summary>
  18. public class HttpHelper
  19. {
  20. public static void init_Request(ref System.Net.HttpWebRequest request)
  21. {
  22. request.Accept = "text/json,*/*;q=0.5";
  23. request.Headers.Add("Accept-Charset", "utf-8;q=0.7,*;q=0.7");
  24. request.Headers.Add("Accept-Encoding", "gzip, deflate, x-gzip, identity; q=0.9");
  25. request.AutomaticDecompression = System.Net.DecompressionMethods.GZip;
  26. request.Timeout = 8000;
  27. }
  28. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  29. {
  30. return true; //总是接受
  31. }
  32. public static System.Net.HttpWebRequest GetHttpWebRequest(string url)
  33. {
  34. HttpWebRequest request = null;
  35. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  36. {
  37. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  38. request = WebRequest.Create(url) as HttpWebRequest;
  39. request.ProtocolVersion = HttpVersion.Version10;
  40. }
  41. else
  42. {
  43. request = WebRequest.Create(url) as HttpWebRequest;
  44. }
  45. return request;
  46. }
  47. public static WebResponse Download(string downloadUrl, long from, long to, string method)
  48. {
  49. for (int i = 0; i < 10; i++)
  50. {
  51. try
  52. {
  53. HttpWebRequest request = HttpHelper.GetHttpWebRequest(downloadUrl);
  54. HttpHelper.init_Request(ref request);
  55. request.Accept = "text/json,*/*;q=0.5";
  56. request.AddRange(from, to);
  57. request.Headers.Add("Accept-Charset", "utf-8;q=0.7,*;q=0.7");
  58. request.Headers.Add("Accept-Encoding", "gzip, deflate, x-gzip, identity; q=0.9");
  59. request.AutomaticDecompression = System.Net.DecompressionMethods.GZip;
  60. request.Timeout = 120000;
  61. request.Method = method;
  62. request.KeepAlive = false;
  63. request.ContentType = "application/json; charset=utf-8";
  64. return request.GetResponse();
  65. }
  66. catch (Exception)
  67. {
  68. Thread.Sleep(100);
  69. }
  70. }
  71. throw new Exception("已断开网络!请检查网络连接后重试下载!");
  72. }
  73. public static string Get(string url, IDictionary<string, string> param)
  74. {
  75. List<string> paramBuilder = new List<string>();
  76. foreach (KeyValuePair<string, string> item in param)
  77. {
  78. paramBuilder.Add(string.Format("{0}={1}", item.Key, item.Value));
  79. }
  80. url = string.Format("{0}?{1}", url.TrimEnd('?'), string.Join(",", paramBuilder.ToArray()));
  81. return Get(url);
  82. }
  83. public static string Get(string url)
  84. {
  85. try
  86. {
  87. HttpWebRequest request = GetHttpWebRequest(url);
  88. if (request != null)
  89. {
  90. string retval = null;
  91. init_Request(ref request);
  92. using (WebResponse Response = request.GetResponse())
  93. {
  94. using (StreamReader reader = new System.IO.StreamReader(Response.GetResponseStream(), System.Text.Encoding.UTF8))
  95. {
  96. retval = reader.ReadToEnd();
  97. }
  98. }
  99. return retval;
  100. }
  101. }
  102. catch
  103. {
  104. }
  105. return null;
  106. }
  107. public static string Post(string url, string data)
  108. {
  109. try
  110. {
  111. HttpWebRequest request = GetHttpWebRequest(url);
  112. if (request != null)
  113. {
  114. string retval = null;
  115. init_Request(ref request);
  116. request.Method = "POST";
  117. request.ServicePoint.Expect100Continue = false;
  118. request.ContentType = "application/json; charset=utf-8";
  119. request.Timeout = 5000;
  120. byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes(data);
  121. request.ContentLength = bytes.Length;
  122. using (Stream stream = request.GetRequestStream())
  123. {
  124. stream.Write(bytes, 0, bytes.Length);
  125. }
  126. using (WebResponse response = request.GetResponse())
  127. {
  128. using (StreamReader reader = new System.IO.StreamReader(response.GetResponseStream()))
  129. {
  130. retval = reader.ReadToEnd();
  131. }
  132. }
  133. return retval;
  134. }
  135. }
  136. catch
  137. {
  138. }
  139. return null;
  140. }
  141. /// <summary>
  142. ///调用Post接口
  143. /// </summary>
  144. /// <param name="request"></param>
  145. /// <returns></returns>
  146. public static string HttpPost(string body, string Url)
  147. {
  148. try
  149. {
  150. Encoding encoding = Encoding.UTF8;
  151. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
  152. request.Method = "POST";
  153. request.Accept = "text/html,application/xhtml+xml,*/*";
  154. request.ContentType = "application/json";
  155. string postDataAES = body;
  156. bool IsParameterEncryption = FileToolsCommon.GetConfigValue("IsParameterEncryption") != "0";
  157. if (IsParameterEncryption)
  158. {
  159. postDataAES = AESHelper.AESEncrypt(body, "XINGHUOLIAOYUAN7");
  160. }
  161. byte[] buffer = encoding.GetBytes(postDataAES);
  162. request.ContentLength = buffer.Length;
  163. request.GetRequestStream().Write(buffer, 0, buffer.Length);
  164. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  165. using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
  166. {
  167. return reader.ReadToEnd();
  168. }
  169. }
  170. catch (Exception ex)
  171. {
  172. // LogHelper.Instance.Debug($"POST接口连接失败,请求参数:{ex.Message}");
  173. return "POST报错:" + ex.Message;
  174. }
  175. }
  176. /// <summary>
  177. /// Post Http请求
  178. /// </summary>
  179. /// <param name="url">请求地址</param>
  180. /// <param name="postData">传输数据</param>
  181. /// <param name="timeout">超时时间</param>
  182. /// <param name="contentType">媒体格式</param>
  183. /// <param name="encode">编码</param>
  184. /// <returns>泛型集合</returns>
  185. public static T PostAndRespSignle<T>(string url, int timeout = 5000, string postData = "", string contentType = "application/json;", string encode = "UTF-8") where T : class
  186. {
  187. if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(encode) && !string.IsNullOrEmpty(contentType) && postData != null)
  188. {
  189. // webRequest.Headers.Add("Authorization", "Bearer " + "SportApiAuthData");
  190. HttpWebResponse webResponse = null;
  191. Stream responseStream = null;
  192. Stream requestStream = null;
  193. StreamReader streamReader = null;
  194. try
  195. {
  196. string postDataAES = postData;
  197. bool IsParameterEncryption = FileToolsCommon.GetConfigValue("IsParameterEncryption") != "0";
  198. if (IsParameterEncryption)
  199. {
  200. postDataAES = AESHelper.AESEncrypt(postData, "XINGHUOLIAOYUAN7");
  201. }
  202. string respstr = GetStreamReader(url, responseStream, requestStream, streamReader, webResponse, timeout, encode, postDataAES, contentType);
  203. return JsonHelper.JsonToObj<T>(respstr);
  204. }
  205. catch (Exception)
  206. {
  207. }
  208. finally
  209. {
  210. if (responseStream != null)
  211. {
  212. responseStream.Dispose();
  213. }
  214. if (webResponse != null)
  215. {
  216. webResponse.Close();
  217. }
  218. if (requestStream != null)
  219. {
  220. requestStream.Dispose();
  221. }
  222. if (streamReader != null)
  223. {
  224. streamReader.Dispose();
  225. }
  226. }
  227. }
  228. return default(T);
  229. }
  230. private static string GetStreamReader(string url, Stream responseStream, Stream requestStream, StreamReader streamReader, WebResponse webResponse, int timeout, string encode, string postData, string contentType)
  231. {
  232. try
  233. {
  234. byte[] data = Encoding.GetEncoding(encode).GetBytes(postData);
  235. HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
  236. webRequest.Method = "POST";
  237. webRequest.ContentType = contentType + ";" + encode;
  238. webRequest.ContentLength = data.Length;
  239. webRequest.Timeout = timeout;
  240. requestStream = webRequest.GetRequestStream();
  241. requestStream.Write(data, 0, data.Length);
  242. webResponse = (HttpWebResponse)webRequest.GetResponse();
  243. responseStream = webResponse.GetResponseStream();
  244. if (responseStream == null) { return ""; }
  245. streamReader = new StreamReader(responseStream, Encoding.GetEncoding(encode));
  246. return streamReader.ReadToEnd();
  247. }
  248. catch (Exception)
  249. {
  250. return null;
  251. }
  252. }
  253. /// <summary>
  254. /// Cookie
  255. /// </summary>
  256. public static CookieContainer cc = new CookieContainer();
  257. /// <summary>
  258. /// Get请求
  259. /// </summary>
  260. /// <param name="serviceaddress">请求地址</param>
  261. /// <param name="strcontent">头</param>
  262. /// <param name="contenttype">参数</param>
  263. /// <param name="header">token</param>
  264. /// <returns></returns>
  265. public static JObject GetFunction(string serviceaddress, string strcontent, string contenttype, string header, int Timeout = 5000)
  266. {
  267. try
  268. {
  269. string serviceAddress = serviceaddress + strcontent;
  270. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
  271. WebHeaderCollection myWebHeaderCollection = request.Headers;
  272. request.CookieContainer = cc;
  273. if (header != "")
  274. {
  275. myWebHeaderCollection.Add("access_token:" + header);
  276. }
  277. request.Method = "GET";
  278. request.ContentType = contenttype;
  279. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  280. string encoding = response.ContentEncoding;
  281. if (encoding == null || encoding.Length < 1)
  282. {
  283. encoding = "UTF-8"; //默认编码
  284. }
  285. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
  286. string retString = reader.ReadToEnd();
  287. //解析josn
  288. JObject jo = JObject.Parse(retString);
  289. return jo;
  290. }
  291. catch (Exception)
  292. {
  293. return null;
  294. }
  295. }
  296. /// <summary>
  297. /// Post请求
  298. /// </summary>
  299. /// <param name="serviceaddress">请求地址</param>
  300. /// <param name="contenttype">头 application/x-www-form-urlencoded</param>
  301. /// <param name="strcontent">参数</param>
  302. /// <param name="header">token</param>
  303. /// <returns></returns>
  304. public static JObject PostFunction(string serviceaddress, string contenttype, string strcontent, string header, int Timeout = 5000)
  305. {
  306. try
  307. {
  308. string serviceAddress = serviceaddress;
  309. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
  310. WebHeaderCollection myWebHeaderCollection = request.Headers;
  311. request.CookieContainer = cc;
  312. //myWebHeaderCollection.Add("Accept", "*/*");
  313. if (header != "")
  314. {
  315. myWebHeaderCollection.Add("access_token:" + header);
  316. }
  317. request.Timeout = Timeout;
  318. request.Method = "POST";
  319. request.ContentType = contenttype;
  320. using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
  321. {
  322. dataStream.Write(strcontent);
  323. dataStream.Close();
  324. }
  325. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  326. string encoding = response.ContentEncoding;
  327. if (encoding == null || encoding.Length < 1)
  328. {
  329. encoding = "UTF-8"; //默认编码
  330. }
  331. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
  332. string retString = reader.ReadToEnd();
  333. retString = retString.Replace("\\r\\n", "");
  334. //解析josn
  335. JObject jo = JObject.Parse(retString);
  336. return jo;
  337. }
  338. catch (Exception ex)
  339. {
  340. LogHelper.WriteErrLog("请求失败(若网络无问题,请重置winsock,解决方法:以管理员方式打开cmd执行 netsh winsock reset 后重启)", ex);
  341. return null;
  342. }
  343. }
  344. /// <summary>
  345. /// 上传方法
  346. /// </summary>
  347. /// <param name="url">webapi地址</param>
  348. /// <param name="files">本地文件路径,单文件默认为string[0]</param>
  349. /// <param name="token"></param>
  350. /// <param name="formFields">参数可不传</param>
  351. /// <returns></returns>
  352. public static JObject UploadFilesToRemoteUrl(string url, string[] files, string token, NameValueCollection formFields = null)
  353. {
  354. string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
  355. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  356. request.ContentType = "multipart/form-data; boundary=" +
  357. boundary;
  358. request.Method = "POST";
  359. request.KeepAlive = true;
  360. Stream memStream = new System.IO.MemoryStream();
  361. byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
  362. boundary + "\r\n");
  363. byte[] endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
  364. boundary + "--");
  365. WebHeaderCollection myWebHeaderCollection = request.Headers;
  366. request.CookieContainer = cc;
  367. if (token != "")
  368. {
  369. myWebHeaderCollection.Add("access_token:" + token);
  370. }
  371. string formdataTemplate = "\r\n--" + boundary +
  372. "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
  373. if (formFields != null)
  374. {
  375. foreach (string key in formFields.Keys)
  376. {
  377. string formitem = string.Format(formdataTemplate, key, formFields[key]);
  378. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  379. memStream.Write(formitembytes, 0, formitembytes.Length);
  380. }
  381. }
  382. string headerTemplate =
  383. "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
  384. "Content-Type: application/octet-stream\r\n\r\n";
  385. for (int i = 0; i < files.Length; i++)
  386. {
  387. memStream.Write(boundarybytes, 0, boundarybytes.Length);
  388. string header = string.Format(headerTemplate, "fileData", files[i]);
  389. byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  390. memStream.Write(headerbytes, 0, headerbytes.Length);
  391. using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
  392. {
  393. byte[] buffer = new byte[1024];
  394. int bytesRead = 0;
  395. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  396. {
  397. memStream.Write(buffer, 0, bytesRead);
  398. }
  399. }
  400. }
  401. //memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  402. request.ContentLength = memStream.Length;
  403. using (Stream requestStream = request.GetRequestStream())
  404. {
  405. memStream.Position = 0;
  406. byte[] tempBuffer = new byte[memStream.Length];
  407. memStream.Read(tempBuffer, 0, tempBuffer.Length);
  408. memStream.Close();
  409. requestStream.Write(tempBuffer, 0, tempBuffer.Length);
  410. }
  411. using (WebResponse response = request.GetResponse())
  412. {
  413. Stream stream2 = response.GetResponseStream();
  414. StreamReader reader2 = new StreamReader(stream2);
  415. JObject a = JObject.Parse(reader2.ReadToEnd());
  416. return a;
  417. }
  418. }
  419. /// <summary>
  420. /// HttpWebRequest 下载
  421. /// </summary>
  422. /// <param name="url">URI</param>
  423. /// <returns></returns>
  424. public static bool GetDataGetHtml(string url, string filePath, string header)
  425. {
  426. try
  427. {
  428. HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
  429. //httpWebRequest.ContentType = "application/x-www-form-urlencoded";
  430. httpWebRequest.Method = "GET";
  431. //httpWebRequest.ContentType = "image/jpeg";
  432. //对发送的数据不使用缓存
  433. httpWebRequest.AllowWriteStreamBuffering = false;
  434. //httpWebRequest.Timeout = 300000;
  435. httpWebRequest.ServicePoint.Expect100Continue = false;
  436. WebHeaderCollection myWebHeaderCollection = httpWebRequest.Headers;
  437. //myWebHeaderCollection.Add("Accept", "*/*");
  438. if (header != "")
  439. {
  440. myWebHeaderCollection.Add("access_token:" + header);
  441. }
  442. HttpWebResponse webRespon = (HttpWebResponse)httpWebRequest.GetResponse();
  443. Stream webStream = webRespon.GetResponseStream();
  444. long length = webRespon.ContentLength;
  445. if (webStream == null)
  446. {
  447. return false;
  448. }
  449. int lengthint = Convert.ToInt32(length);
  450. //int num = lengthint / 1024;
  451. //int count = 0;
  452. //M_DownloadInfo.totalCount = lengthint / 1024;
  453. //M_DownloadInfo.downloadCount = 0;
  454. Stream stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
  455. byte[] bArr = new byte[1024];
  456. int size = webStream.Read(bArr, 0, bArr.Length);
  457. while (size > 0)
  458. {
  459. stream.Write(bArr, 0, size);
  460. size = webStream.Read(bArr, 0, bArr.Length);
  461. //M_DownloadInfo.downloadCount = M_DownloadInfo.downloadCount + 1;
  462. }
  463. webRespon.Close();
  464. stream.Close();
  465. webStream.Close();
  466. return true;
  467. }
  468. catch (Exception)
  469. {
  470. //LogHelper.WriteErrLog("请求失败:" + ex.Message, ex);
  471. return false;
  472. }
  473. }
  474. /// <summary>
  475. /// 上传文件流
  476. /// 创建人:赵耀
  477. /// 创建时间:2020年9月5日
  478. /// </summary>
  479. /// <param name="url">URL</param>
  480. /// <param name="databyte">文件数据流</param>
  481. /// <param name="filename">文件名</param>
  482. /// <param name="formFields">参数 可不传</param>
  483. public static JObject UploadRequestflow(string url, byte[] databyte, string filename, NameValueCollection formFields = null)
  484. {
  485. JObject jobResult = null;
  486. // 时间戳,用做boundary
  487. string boundary = "-----" + DateTime.Now.Ticks.ToString("x");
  488. byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
  489. //根据uri创建HttpWebRequest对象
  490. HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
  491. httpReq.ContentType = "multipart/form-data; boundary=" + boundary;
  492. httpReq.Method = "POST";
  493. httpReq.KeepAlive = true;
  494. //httpReq.Timeout = 300000;
  495. //httpReq.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存
  496. httpReq.Credentials = CredentialCache.DefaultCredentials;
  497. try
  498. {
  499. Stream postStream = httpReq.GetRequestStream();
  500. //参数
  501. const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
  502. if (formFields != null)
  503. {
  504. foreach (string key in formFields.Keys)
  505. {
  506. postStream.Write(boundarybytes, 0, boundarybytes.Length);
  507. string formitem = string.Format(formdataTemplate, key, formFields[key]);
  508. byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
  509. postStream.Write(formitembytes, 0, formitembytes.Length);
  510. }
  511. }
  512. postStream.Write(boundarybytes, 0, boundarybytes.Length);
  513. const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
  514. //文件头
  515. string header = string.Format(headerTemplate, "file", filename);
  516. byte[] headerbytes = Encoding.UTF8.GetBytes(header);
  517. postStream.Write(headerbytes, 0, headerbytes.Length);
  518. //文件流
  519. postStream.Write(databyte, 0, databyte.Length);
  520. //结束边界
  521. byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
  522. postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
  523. postStream.Close();
  524. //获取服务器端的响应
  525. using (HttpWebResponse response = (HttpWebResponse)httpReq.GetResponse())
  526. {
  527. Stream receiveStream = response.GetResponseStream();
  528. StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
  529. string returnValue = readStream.ReadToEnd();
  530. jobResult = JObject.Parse(returnValue);
  531. response.Close();
  532. readStream.Close();
  533. }
  534. return jobResult;
  535. }
  536. catch (Exception ex)
  537. {
  538. LogHelper.WriteErrLog("【文件上传】" + ex.Message, ex);
  539. return null;
  540. }
  541. finally
  542. {
  543. httpReq = null;
  544. }
  545. }
  546. /// <summary>
  547. /// Post Http请求
  548. /// </summary>
  549. /// <param name="url"></param>
  550. /// <param name="postData"></param>
  551. /// <param name="timeout"></param>
  552. /// <param name="contentType"></param>
  553. /// <param name="encode"></param>
  554. /// <returns>响应流字符串</returns>
  555. public static string PostAndRespStr(string url, string postData = "", int timeout = 5000, string contentType = "application/json;", string encode = "UTF-8")
  556. {
  557. if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(encode) && !string.IsNullOrEmpty(contentType) && postData != null)
  558. {
  559. HttpWebResponse webResponse = null;
  560. Stream responseStream = null;
  561. Stream requestStream = null;
  562. StreamReader streamReader = null;
  563. try
  564. {
  565. string postDataAES = postData;
  566. bool IsParameterEncryption = FileToolsCommon.GetConfigValue("IsParameterEncryption") != "0";
  567. if (IsParameterEncryption)
  568. {
  569. postDataAES = AESHelper.AESEncrypt(postData, "XINGHUOLIAOYUAN7");
  570. }
  571. return GetStreamReader(url, responseStream, requestStream, streamReader, webResponse, timeout, encode, postDataAES, contentType);
  572. }
  573. catch (Exception)
  574. {
  575. }
  576. finally
  577. {
  578. if (responseStream != null)
  579. {
  580. responseStream.Dispose();
  581. }
  582. if (webResponse != null)
  583. {
  584. webResponse.Close();
  585. }
  586. if (requestStream != null)
  587. {
  588. requestStream.Dispose();
  589. }
  590. if (streamReader != null)
  591. {
  592. streamReader.Dispose();
  593. }
  594. }
  595. }
  596. return null;
  597. }
  598. /// <summary>
  599. /// 获取公网IP和地址,失败则获取局域网IP
  600. /// </summary>
  601. /// <param name="AddressIP">IP地址</param>
  602. /// <param name="Address">地址</param>
  603. /// <returns></returns>
  604. public static bool GetAddressIP(out string AddressIP, out string Address)
  605. {
  606. AddressIP = "";
  607. Address = "";
  608. try
  609. {
  610. //请求搜狐获取公网IP,获取失败后获取局域网IP
  611. WebRequest request = WebRequest.Create("http://pv.sohu.com/cityjson?ie=utf-8");
  612. request.Timeout = 10000;
  613. WebResponse response = request.GetResponse();
  614. Stream resStream = response.GetResponseStream();
  615. StreamReader sr = new StreamReader(resStream, System.Text.Encoding.UTF8);
  616. string htmlinfo = sr.ReadToEnd();
  617. string jsonStr = htmlinfo.Substring(htmlinfo.IndexOf("{"), htmlinfo.LastIndexOf("}") - htmlinfo.IndexOf("{") + 1);
  618. JObject obj = JObject.Parse(jsonStr);
  619. AddressIP = obj["cip"].ToString();
  620. Address = obj["cname"].ToString();
  621. resStream.Close();
  622. sr.Close();
  623. return true;
  624. //Regex r = new Regex("((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|[1-9])", RegexOptions.None);
  625. //Match mc = r.Match(htmlinfo);
  626. //AddressIP = mc.Groups[0].Value;
  627. }
  628. catch (Exception)
  629. {
  630. //获取本地局域网IP
  631. foreach (System.Net.IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
  632. {
  633. if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
  634. {
  635. AddressIP = _IPAddress.ToString();
  636. }
  637. }
  638. return false;
  639. }
  640. }
  641. }
  642. }