WebHelper.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. using System.Collections.Generic;
  2. using System.IO;
  3. using System.Net;
  4. using System.Text;
  5. using System.Web;
  6. using System;
  7. using System.Text.RegularExpressions;
  8. using System.Web.SessionState;
  9. using System.Net.Security;
  10. using System.Security.Cryptography.X509Certificates;
  11. namespace LeaRun.Util
  12. {
  13. /// <summary>
  14. /// Web操作
  15. /// </summary>
  16. public static class WebHelper
  17. {
  18. #region Host(获取主机名)
  19. /// <summary>
  20. /// 获取主机名,即域名,
  21. /// 范例:用户输入网址http://www.a.com/b.htm?a=1&amp;b=2,
  22. /// 返回值为: www.a.com
  23. /// </summary>
  24. public static string Host
  25. {
  26. get
  27. {
  28. return HttpContext.Current.Request.Url.Host;
  29. }
  30. }
  31. #endregion
  32. #region ResolveUrl(解析相对Url)
  33. /// <summary>
  34. /// 解析相对Url
  35. /// </summary>
  36. /// <param name="relativeUrl">相对Url</param>
  37. public static string ResolveUrl(string relativeUrl)
  38. {
  39. if (string.IsNullOrWhiteSpace(relativeUrl))
  40. return string.Empty;
  41. relativeUrl = relativeUrl.Replace("\\", "/");
  42. if (relativeUrl.StartsWith("/"))
  43. return relativeUrl;
  44. if (relativeUrl.Contains("://"))
  45. return relativeUrl;
  46. return VirtualPathUtility.ToAbsolute(relativeUrl);
  47. }
  48. #endregion
  49. #region HtmlEncode(对html字符串进行编码)
  50. /// <summary>
  51. /// 对html字符串进行编码
  52. /// </summary>
  53. /// <param name="html">html字符串</param>
  54. public static string HtmlEncode(string html)
  55. {
  56. return HttpUtility.HtmlEncode(html);
  57. }
  58. /// <summary>
  59. /// 对html字符串进行解码
  60. /// </summary>
  61. /// <param name="html">html字符串</param>
  62. public static string HtmlDecode(string html)
  63. {
  64. return HttpUtility.HtmlDecode(html);
  65. }
  66. #endregion
  67. #region UrlEncode(对Url进行编码)
  68. /// <summary>
  69. /// 对Url进行编码
  70. /// </summary>
  71. /// <param name="url">url</param>
  72. /// <param name="isUpper">编码字符是否转成大写,范例,"http://"转成"http%3A%2F%2F"</param>
  73. public static string UrlEncode(string url, bool isUpper = false)
  74. {
  75. return UrlEncode(url, Encoding.UTF8, isUpper);
  76. }
  77. /// <summary>
  78. /// 对Url进行编码
  79. /// </summary>
  80. /// <param name="url">url</param>
  81. /// <param name="encoding">字符编码</param>
  82. /// <param name="isUpper">编码字符是否转成大写,范例,"http://"转成"http%3A%2F%2F"</param>
  83. public static string UrlEncode(string url, Encoding encoding, bool isUpper = false)
  84. {
  85. var result = HttpUtility.UrlEncode(url, encoding);
  86. if (!isUpper)
  87. return result;
  88. return GetUpperEncode(result);
  89. }
  90. /// <summary>
  91. /// 获取大写编码字符串
  92. /// </summary>
  93. private static string GetUpperEncode(string encode)
  94. {
  95. var result = new StringBuilder();
  96. int index = int.MinValue;
  97. for (int i = 0; i < encode.Length; i++)
  98. {
  99. string character = encode[i].ToString();
  100. if (character == "%")
  101. index = i;
  102. if (i - index == 1 || i - index == 2)
  103. character = character.ToUpper();
  104. result.Append(character);
  105. }
  106. return result.ToString();
  107. }
  108. #endregion
  109. #region UrlDecode(对Url进行解码)
  110. /// <summary>
  111. /// 对Url进行解码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码
  112. /// </summary>
  113. /// <param name="url">url</param>
  114. public static string UrlDecode(string url)
  115. {
  116. return HttpUtility.UrlDecode(url);
  117. }
  118. /// <summary>
  119. /// 对Url进行解码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码
  120. /// </summary>
  121. /// <param name="url">url</param>
  122. /// <param name="encoding">字符编码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码</param>
  123. public static string UrlDecode(string url, Encoding encoding)
  124. {
  125. return HttpUtility.UrlDecode(url, encoding);
  126. }
  127. #endregion
  128. #region Session操作
  129. /// <summary>
  130. /// 写Session
  131. /// </summary>
  132. /// <typeparam name="T">Session键值的类型</typeparam>
  133. /// <param name="key">Session的键名</param>
  134. /// <param name="value">Session的键值</param>
  135. public static void WriteSession<T>(string key, T value)
  136. {
  137. //if (key.IsEmpty())
  138. // return;
  139. HttpContext.Current.Session[key] = value;
  140. HttpContext.Current.Session.Timeout = 60;//设置默认的时间60分钟
  141. }
  142. /// <summary>
  143. /// 写Session
  144. /// </summary>
  145. /// <param name="key">Session的键名</param>
  146. /// <param name="value">Session的键值</param>
  147. public static void WriteSession(string key, string value)
  148. {
  149. WriteSession<string>(key, value);
  150. }
  151. /// <summary>
  152. /// 读取Session的值
  153. /// </summary>
  154. /// <param name="key">Session的键名</param>
  155. public static string GetSession(string key)
  156. {
  157. //if (key.IsEmpty())
  158. // return string.Empty;
  159. if (HttpContext.Current.Session[key] != null)
  160. return HttpContext.Current.Session[key] as string;
  161. else
  162. return "";
  163. }
  164. /// <summary>
  165. /// 删除指定Session
  166. /// </summary>
  167. /// <param name="key">Session的键名</param>
  168. public static void RemoveSession(string key)
  169. {
  170. //if (key.IsEmpty())
  171. // return;
  172. HttpContext.Current.Session.Contents.Remove(key);
  173. }
  174. #endregion
  175. #region Cookie操作
  176. /// <summary>
  177. /// 写cookie值
  178. /// </summary>
  179. /// <param name="strName">名称</param>
  180. /// <param name="strValue">值</param>
  181. public static void WriteCookie(string strName, string strValue)
  182. {
  183. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  184. if (cookie == null)
  185. {
  186. cookie = new HttpCookie(strName);
  187. }
  188. cookie.Value = strValue;
  189. HttpContext.Current.Response.AppendCookie(cookie);
  190. }
  191. /// <summary>
  192. /// 写cookie值
  193. /// </summary>
  194. /// <param name="strName">名称</param>
  195. /// <param name="strValue">值</param>
  196. /// <param name="strValue">过期时间(分钟)</param>
  197. public static void WriteCookie(string strName, string strValue, int expires)
  198. {
  199. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  200. if (cookie == null)
  201. {
  202. cookie = new HttpCookie(strName);
  203. }
  204. cookie.Value = strValue;
  205. cookie.Expires = DateTime.Now.AddMinutes(expires);
  206. HttpContext.Current.Response.AppendCookie(cookie);
  207. }
  208. /// <summary>
  209. /// 读cookie值
  210. /// </summary>
  211. /// <param name="strName">名称</param>
  212. /// <returns>cookie值</returns>
  213. public static string GetCookie(string strName)
  214. {
  215. if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
  216. {
  217. return HttpContext.Current.Request.Cookies[strName].Value.ToString();
  218. }
  219. return "";
  220. }
  221. /// <summary>
  222. /// 删除Cookie对象
  223. /// </summary>
  224. /// <param name="CookiesName">Cookie对象名称</param>
  225. public static void RemoveCookie(string CookiesName)
  226. {
  227. HttpCookie objCookie = new HttpCookie(CookiesName.Trim());
  228. objCookie.Expires = DateTime.Now.AddYears(-5);
  229. HttpContext.Current.Response.Cookies.Add(objCookie);
  230. }
  231. #endregion
  232. #region GetFileControls(获取客户端文件控件集合)
  233. /// <summary>
  234. /// 获取有效客户端文件控件集合,文件控件必须上传了内容,为空将被忽略,
  235. /// 注意:Form标记必须加入属性 enctype="multipart/form-data",服务器端才能获取客户端file控件.
  236. /// </summary>
  237. public static List<HttpPostedFile> GetFileControls()
  238. {
  239. var result = new List<HttpPostedFile>();
  240. var files = HttpContext.Current.Request.Files;
  241. if (files.Count == 0)
  242. return result;
  243. for (int i = 0; i < files.Count; i++)
  244. {
  245. var file = files[i];
  246. if (file.ContentLength == 0)
  247. continue;
  248. result.Add(files[i]);
  249. }
  250. return result;
  251. }
  252. #endregion
  253. #region GetFileControl(获取第一个有效客户端文件控件)
  254. /// <summary>
  255. /// 获取第一个有效客户端文件控件,文件控件必须上传了内容,为空将被忽略,
  256. /// 注意:Form标记必须加入属性 enctype="multipart/form-data",服务器端才能获取客户端file控件.
  257. /// </summary>
  258. public static HttpPostedFile GetFileControl()
  259. {
  260. var files = GetFileControls();
  261. if (files == null || files.Count == 0)
  262. return null;
  263. return files[0];
  264. }
  265. #endregion
  266. #region HttpWebRequest(请求网络资源)
  267. /// <summary>
  268. /// 请求网络资源,返回响应的文本
  269. /// </summary>
  270. /// <param name="url">网络资源地址</param>
  271. public static string HttpWebRequest(string url)
  272. {
  273. return HttpWebRequest(url, string.Empty, Encoding.GetEncoding("utf-8"));
  274. }
  275. /// <summary>
  276. /// 请求网络资源,返回响应的文本
  277. /// </summary>
  278. /// <param name="url">网络资源Url地址</param>
  279. /// <param name="parameters">提交的参数,格式:参数1=参数值1&amp;参数2=参数值2</param>
  280. public static string HttpWebRequest(string url, string parameters)
  281. {
  282. return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), "POST");
  283. }
  284. /// <summary>
  285. /// 请求网络资源,返回响应的文本
  286. /// </summary>
  287. /// <param name="url">网络资源Url地址</param>
  288. /// <param name="parameters"></param>
  289. public static string HttpWebRequest(string url, string parameters, string contentType, string Authorization, string app_key)
  290. {
  291. return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), "POST", contentType, Authorization, app_key);
  292. }
  293. /// <summary>
  294. /// 请求网络资源,返回响应的文本
  295. /// </summary>
  296. /// <param name="url">网络资源Url地址</param>
  297. /// <param name="parameters"></param>
  298. public static string HttpWebRequest(string url, string parameters, string mehtod, string contentType, string Authorization, string app_key)
  299. {
  300. return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), mehtod, contentType, Authorization, app_key);
  301. }
  302. /// <summary>
  303. /// 请求网络资源,返回响应的文本
  304. /// </summary>
  305. /// <param name="url">网络资源地址</param>
  306. /// <param name="parameters">提交的参数,格式:参数1=参数值1&amp;参数2=参数值2</param>
  307. /// <param name="encoding">字符编码</param>
  308. /// <param name="isPost">是否Post提交</param>
  309. /// <param name="contentType">内容类型</param>
  310. /// <param name="cookie">Cookie容器</param>
  311. /// <param name="timeout">超时时间</param>
  312. public static string HttpWebRequest(string url, string parameters, Encoding encoding, string mehtod = "POST",
  313. string contentType = "application/x-www-form-urlencoded", string Authorization = null, string app_key = null, CookieContainer cookie = null, int timeout = 120000)
  314. {
  315. HttpWebRequest request = null;
  316. try
  317. {
  318. //如果是发送HTTPS请求
  319. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  320. {
  321. //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
  322. //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  323. ////X509Certificate cerCaiShang = new X509Certificate(System.Web.HttpContext.Current.Server.MapPath(Config.GetValue("NB_PfxPath")), Config.GetValue("NB_PfxKey"));
  324. ////X509Certificate2 cerCaiShang = GetSentosaCertificate();
  325. //X509Certificate2 cerCaiShang = new X509Certificate2(Config.GetValue("NB_PfxPath"), Config.GetValue("NB_PfxKey"));
  326. //request = WebRequest.Create(url) as HttpWebRequest;
  327. //request.ClientCertificates.Add(cerCaiShang);
  328. //request.ProtocolVersion = HttpVersion.Version10;
  329. }
  330. else
  331. {
  332. request = WebRequest.Create(url) as HttpWebRequest;
  333. }
  334. request.Timeout = timeout;
  335. if (!string.IsNullOrEmpty(Authorization))
  336. {
  337. request.Headers["Authorization"] = Authorization;
  338. }
  339. if (!string.IsNullOrEmpty(app_key))
  340. {
  341. request.Headers["app_key"] = app_key;
  342. }
  343. request.CookieContainer = cookie;
  344. request.ContentType = contentType;
  345. request.Method = mehtod;
  346. if (mehtod == "POST")
  347. {
  348. byte[] postData = encoding.GetBytes(parameters);
  349. request.Method = "POST";
  350. request.ContentType = contentType;
  351. request.ContentLength = postData.Length;
  352. using (Stream stream = request.GetRequestStream())
  353. {
  354. stream.Write(postData, 0, postData.Length);
  355. }
  356. }
  357. if (mehtod == "PUT")
  358. {
  359. using (StreamWriter requestStream = new StreamWriter(request.GetRequestStream()))
  360. {
  361. requestStream.Write(parameters);
  362. }
  363. }
  364. var response = (HttpWebResponse)request.GetResponse();
  365. string result;
  366. using (Stream stream = response.GetResponseStream())
  367. {
  368. if (stream == null)
  369. return string.Empty;
  370. using (var reader = new StreamReader(stream, encoding))
  371. {
  372. result = reader.ReadToEnd();
  373. }
  374. }
  375. return result;
  376. }
  377. catch (Exception ex)
  378. {
  379. throw ex;
  380. }
  381. }
  382. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  383. {
  384. return true;
  385. }
  386. private static X509Certificate2 GetSentosaCertificate()
  387. {
  388. X509Store userCaStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
  389. try
  390. {
  391. userCaStore.Open(OpenFlags.ReadOnly);
  392. X509Certificate2Collection certificatesInStore = userCaStore.Certificates;
  393. X509Certificate2Collection findResult = certificatesInStore.Find(X509FindType.FindBySubjectName, "server", true);
  394. X509Certificate2 clientCertificate = null;
  395. if (findResult.Count == 1)
  396. {
  397. clientCertificate = findResult[0];
  398. }
  399. else
  400. {
  401. throw new Exception("Unable to locate the correct client certificate.");
  402. }
  403. return clientCertificate;
  404. }
  405. catch
  406. {
  407. throw;
  408. }
  409. finally
  410. {
  411. userCaStore.Close();
  412. }
  413. }
  414. #endregion
  415. #region 去除HTML标记
  416. /// <summary>
  417. /// 去除HTML标记
  418. /// </summary>
  419. /// <param name="NoHTML">包括HTML的源码 </param>
  420. /// <returns>已经去除后的文字</returns>
  421. public static string NoHtml(string Htmlstring)
  422. {
  423. //删除脚本
  424. Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
  425. //删除HTML
  426. Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
  427. Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
  428. Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
  429. Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
  430. Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
  431. Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
  432. Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
  433. Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
  434. Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
  435. Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
  436. Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
  437. Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
  438. Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
  439. Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
  440. Htmlstring = Regex.Replace(Htmlstring, @"&hellip;", "", RegexOptions.IgnoreCase);
  441. Htmlstring = Regex.Replace(Htmlstring, @"&mdash;", "", RegexOptions.IgnoreCase);
  442. Htmlstring = Regex.Replace(Htmlstring, @"&ldquo;", "", RegexOptions.IgnoreCase);
  443. Htmlstring.Replace("<", "");
  444. Htmlstring = Regex.Replace(Htmlstring, @"&rdquo;", "", RegexOptions.IgnoreCase);
  445. Htmlstring.Replace(">", "");
  446. Htmlstring.Replace("\r\n", "");
  447. Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
  448. return Htmlstring;
  449. }
  450. #endregion
  451. #region 格式化文本(防止SQL注入)
  452. /// <summary>
  453. /// 格式化文本(防止SQL注入)
  454. /// </summary>
  455. /// <param name="str"></param>
  456. /// <returns></returns>
  457. public static string Formatstr(string html)
  458. {
  459. System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  460. System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  461. System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  462. System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  463. System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  464. System.Text.RegularExpressions.Regex regex10 = new System.Text.RegularExpressions.Regex(@"select", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  465. System.Text.RegularExpressions.Regex regex11 = new System.Text.RegularExpressions.Regex(@"update", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  466. System.Text.RegularExpressions.Regex regex12 = new System.Text.RegularExpressions.Regex(@"delete", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  467. html = regex1.Replace(html, ""); //过滤<script></script>标记
  468. html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
  469. html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
  470. html = regex4.Replace(html, ""); //过滤iframe
  471. html = regex10.Replace(html, "s_elect");
  472. html = regex11.Replace(html, "u_pudate");
  473. html = regex12.Replace(html, "d_elete");
  474. html = html.Replace("'", "’");
  475. html = html.Replace("&nbsp;", " ");
  476. return html;
  477. }
  478. #endregion
  479. #region 根据OneNet平台的鉴权修改Http请求
  480. /// <summary>
  481. /// 请求网络资源,返回响应的文本
  482. /// </summary>
  483. /// <param name="url">网络资源地址</param>
  484. /// <param name="parameters">提交的参数,格式:参数1=参数值1&amp;参数2=参数值2</param>
  485. /// <param name="encoding">字符编码</param>
  486. /// <param name="isPost">是否Post提交</param>
  487. /// <param name="contentType">内容类型</param>
  488. /// <param name="cookie">Cookie容器</param>
  489. /// <param name="timeout">超时时间</param>
  490. public static string HttpWebRequest_oneNet(string url, string parameters, Encoding encoding, string mehtod = "POST",
  491. string contentType = "application/x-www-form-urlencoded", string Authorization = null, string api_key = null, CookieContainer cookie = null, int timeout = 120000)
  492. {
  493. mehtod = mehtod.ToUpper();
  494. HttpWebRequest request = null;
  495. try
  496. {
  497. //如果是发送HTTPS请求
  498. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  499. {
  500. //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
  501. //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  502. ////X509Certificate cerCaiShang = new X509Certificate(System.Web.HttpContext.Current.Server.MapPath(Config.GetValue("NB_PfxPath")), Config.GetValue("NB_PfxKey"));
  503. ////X509Certificate2 cerCaiShang = GetSentosaCertificate();
  504. //X509Certificate2 cerCaiShang = new X509Certificate2(Config.GetValue("NB_PfxPath"), Config.GetValue("NB_PfxKey"));
  505. //request = WebRequest.Create(url) as HttpWebRequest;
  506. //request.ClientCertificates.Add(cerCaiShang);
  507. //request.ProtocolVersion = HttpVersion.Version10;
  508. }
  509. else
  510. {
  511. request = WebRequest.Create(url) as HttpWebRequest;
  512. }
  513. request.Timeout = timeout;
  514. if (!string.IsNullOrEmpty(Authorization))
  515. {
  516. request.Headers["Authorization"] = Authorization;
  517. }
  518. if (!string.IsNullOrEmpty(api_key))
  519. {
  520. request.Headers["api-key"] = api_key;
  521. }
  522. request.CookieContainer = cookie;
  523. request.ContentType = contentType;
  524. request.Method = mehtod;
  525. if (mehtod == "POST")
  526. {
  527. byte[] postData = encoding.GetBytes(parameters);
  528. request.Method = "POST";
  529. request.ContentType = contentType;
  530. request.ContentLength = postData.Length;
  531. using (Stream stream = request.GetRequestStream())
  532. {
  533. stream.Write(postData, 0, postData.Length);
  534. }
  535. }
  536. if (mehtod == "PUT")
  537. {
  538. using (StreamWriter requestStream = new StreamWriter(request.GetRequestStream()))
  539. {
  540. requestStream.Write(parameters);
  541. }
  542. }
  543. var response = (HttpWebResponse)request.GetResponse();
  544. string result;
  545. using (Stream stream = response.GetResponseStream())
  546. {
  547. if (stream == null)
  548. return string.Empty;
  549. using (var reader = new StreamReader(stream, encoding))
  550. {
  551. result = reader.ReadToEnd();
  552. }
  553. }
  554. return result;
  555. }
  556. catch (Exception ex)
  557. {
  558. return "接口调用错误";
  559. }
  560. }
  561. /// <summary>
  562. /// 请求网络资源,返回响应的文本 HttpWebRequest_oneNet(string url, string parameters, string mehtod, string contentType, string Authorization, string api_key)
  563. /// </summary>
  564. /// <param name="url">请求地址</param>
  565. /// <param name="parameters">参数</param>
  566. /// <param name="mehtod">请求方式</param>
  567. /// <param name="contentType"></param>
  568. /// <param name="Authorization"></param>
  569. /// <param name="api_key"></param>
  570. /// <returns></returns>
  571. //public static string HttpWebRequest_oneNet(string url, string parameters, string mehtod, string contentType, string Authorization, string api_key)
  572. //{
  573. // if (api_key == null)
  574. // {
  575. // api_key = Config.GetValue("APIkey");
  576. // }
  577. // return HttpWebRequest_oneNet(url, parameters, Encoding.GetEncoding("utf-8"), mehtod, contentType, Authorization, api_key);
  578. //}
  579. #endregion
  580. }
  581. }