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

HttpHelper.cs 29KB

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