1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Http;
  7. using System.Net.Http.Headers;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Web;
  11.  
  12. namespace Nop.Core.Utils
  13. {
  14. public static class RequestUtility
  15. {
  16. ///
  17. /// 使用Get方法获取字符串结果(暂时没有加入Cookie)
  18. ///
  19.  
  20. ///
  21. ///
  22. public static string HttpGet(string url, Encoding encoding = null)
  23. {
  24. WebClient wc = new WebClient();
  25. wc.Encoding = encoding ?? Encoding.UTF8;
  26. //if (encoding != null)
  27. //{
  28. // wc.Encoding = encoding;
  29. //}
  30. return wc.DownloadString(url);
  31. }
  32.  
  33. public static dynamic HttpGet(string url)
  34. {
  35. HttpClient client = new HttpClient();
  36. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  37.  
  38. var response = client.GetAsync(url).Result;
  39.  
  40. //result返回值
  41. string result = response.Content.ReadAsStringAsync().Result;
  42.  
  43. return result;
  44. }
  45.  
  46. ///
  47. /// Post数据
  48. ///
  49.  
  50. /// 模型
  51. /// server uri
  52. /// 数据模型
  53. ///
  54. public static string Put(string requestUri, T model, IDictionary parameters = null)
  55. {
  56. HttpClient client = new HttpClient();
  57. if (parameters != null && parameters.Count > 0)
  58. {
  59. foreach (var item in parameters)
  60. {
  61. client.DefaultRequestHeaders.Add(item.Key, item.Value);
  62. }
  63. }
  64.  
  65. HttpResponseMessage message = client.PutAsJsonAsync(requestUri, model).Result;
  66. if (message.IsSuccessStatusCode)
  67. {
  68. return message.Content.ReadAsStringAsync().Result;
  69. }
  70. return null;
  71.  
  72. }
  73.  
  74. ///
  75. /// 使用Get方法获取字符串结果(暂时没有加入Cookie),parameters字典里面东西会通过循环在request.Headers中添加
  76. ///
  77.  
  78. ///
  79. ///
  80. public static string HttpGet(string url, IDictionary parameters = null, Encoding encoding = null)
  81. {
  82. Encoding readCoding = encoding ?? Encoding.UTF8;
  83.  
  84. Uri requestUri = new Uri(url);
  85. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
  86. request.UserAgent = "mozilla/4.0 (compatible; msie 6.0; windows 2000)";
  87. request.Method = "Get";
  88. request.ContentType = "application/x-www-form-urlencoded";
  89.  
  90. if (parameters != null && parameters.Count > 0)
  91. {
  92. foreach (var item in parameters)
  93. {
  94. request.Headers.Add(item.Key, item.Value);
  95. }
  96. }
  97.  
  98. HttpWebResponse response = null;
  99. try
  100. {
  101. try
  102. {
  103. response = (HttpWebResponse)request.GetResponse();
  104. }
  105. catch (WebException ex)
  106. {
  107. //若是远程服务器抛出了异常,则捕获并解析
  108. response = (HttpWebResponse)ex.Response;
  109. }
  110.  
  111. using (StreamReader sr = new StreamReader(response.GetResponseStream(), readCoding))
  112. {
  113. string content = sr.ReadToEnd();
  114. return content;
  115. }
  116. }
  117. finally
  118. {
  119. //释放请求的资源
  120. if (response != null)
  121. {
  122. response.Close();
  123. response = null;
  124. }
  125. if (request != null)
  126. {
  127. request.Abort();
  128. }
  129. }
  130. }
  131.  
  132. ///
  133. ///
  134. ///
  135.  
  136. ///
  137. /// 例如Encoding.UTF8.GetBytes(json.Serialize(new { email = "123456@qq.com", password = "111111" }))
  138. /// 字典里面东西会通过循环在request.Headers中添加
  139. ///
  140. ///
  141. public static string HttpPost(string url, byte[] postStream, IDictionary parameters = null, Encoding encoding = null)
  142. {
  143. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  144. request.ProtocolVersion = HttpVersion.Version11;
  145. request.Method = "POST";
  146.  
  147. if (parameters != null && parameters.Count > 0)
  148. {
  149. foreach (var item in parameters)
  150. {
  151. request.Headers.Add(item.Key, item.Value);
  152. }
  153. }
  154.  
  155. request.ContentType = "application/json;charset=utf-8";
  156. request.Accept = "application/json";
  157.  
  158. request.Timeout = 60 * 2 * 1000; // 同步接口 调用时间2分钟
  159. request.ServicePoint.Expect100Continue = false;
  160.  
  161. HttpWebResponse response = null;
  162. try
  163. {
  164. postStream = postStream ?? new byte[] { };
  165. request.ContentLength = postStream.Length;
  166. var requestStream = request.GetRequestStream();
  167. requestStream.Write(postStream, 0, postStream.Length);
  168. requestStream.Close();
  169. response = (HttpWebResponse)request.GetResponse();
  170. using (var responseStream = response.GetResponseStream())
  171. {
  172. if (responseStream != null)
  173. {
  174. using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8))
  175. {
  176. return myStreamReader.ReadToEnd();
  177. }
  178. }
  179. }
  180. }
  181. catch (Exception ex)
  182. {
  183.  
  184. }
  185. finally
  186. {
  187. if (response != null)
  188. {
  189. response.Close();
  190. }
  191. request.Abort();
  192. }
  193. return "";
  194. }
  195.  
  196. ///
  197. /// Post数据
  198. ///
  199.  
  200. /// 模型
  201. /// server uri
  202. /// 数据模型
  203. ///
  204. public static string Post(string requestUri, T model, IDictionary parameters = null)
  205. {
  206. HttpClient client = new HttpClient();
  207. if (parameters != null && parameters.Count > 0)
  208. {
  209. foreach (var item in parameters)
  210. {
  211. client.DefaultRequestHeaders.Add(item.Key, item.Value);
  212. }
  213. }
  214.  
  215. HttpResponseMessage message = client.PostAsJsonAsync(requestUri, model).Result;
  216. if (message.IsSuccessStatusCode)
  217. {
  218. return message.Content.ReadAsStringAsync().Result;
  219. }
  220. return null;
  221.  
  222. }
  223. ///
  224. /// 使用Post方法获取字符串结果
  225. ///
  226.  
  227. ///
  228. public static string HttpPost(string url, CookieContainer cookieContainer = null, Dictionary formData = null, Encoding encoding = null)
  229. {
  230. return HttpPost(url, cookieContainer, formData, encoding, 12000);
  231. }
  232. public static string HttpPost(string url, CookieContainer cookieContainer = null, Dictionary formData = null, Encoding encoding = null, int timeout = 20)
  233. {
  234. string dataString = GetQueryString(formData);
  235. var formDataBytes = formData == null ? new byte[0] : (encoding == null ? Encoding.UTF8.GetBytes(dataString) : encoding.GetBytes(dataString));
  236. using (MemoryStream ms = new MemoryStream())
  237. {
  238. ms.Write(formDataBytes, 0, formDataBytes.Length);
  239. ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
  240. string ret = HttpPost(url, cookieContainer, ms, false, encoding, timeout);
  241. return ret;
  242. }
  243. }
  244. ///
  245. /// 使用Post方法获取字符串结果
  246. ///
  247.  
  248. ///
  249. ///
  250. public static string HttpPost(string url, CookieContainer cookieContainer = null, string fileName = null, Encoding encoding = null)
  251. {
  252. //读取文件
  253. FileStream fileStream = null;
  254. if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
  255. {
  256. fileStream = new FileStream(fileName, FileMode.Open);
  257. }
  258. return HttpPost(url, cookieContainer, fileStream, true, encoding);
  259. }
  260.  
  261. ///
  262. /// 使用Post方法获取字符串结果
  263. ///
  264.  
  265. ///
  266. ///
  267. ///
  268. /// postStreams是否是文件流
  269. ///
  270. public static string HttpPost(string url, CookieContainer cookieContainer = null, Stream postStream = null, bool isFile = false, Encoding encoding = null, int timeout = 1200000)
  271. {
  272. ServicePointManager.DefaultConnectionLimit = 200;
  273. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  274. request.Method = "POST";
  275. request.ContentType = "application/x-www-form-urlencoded";
  276. request.ContentLength = postStream != null ? postStream.Length : 0;
  277. request.Timeout = timeout;
  278. if (cookieContainer != null)
  279. {
  280. request.CookieContainer = cookieContainer;
  281. }
  282. if (postStream != null)
  283. {
  284. //postStream.Position = 0;
  285.  
  286. //上传文件流
  287. Stream requestStream = request.GetRequestStream();
  288.  
  289. byte[] buffer = new byte[1024];
  290. int bytesRead = 0;
  291. while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
  292. {
  293. requestStream.Write(buffer, 0, bytesRead);
  294. }
  295.  
  296. postStream.Close();//关闭文件访问
  297. }
  298. HttpWebResponse response = null;
  299. try
  300. {
  301. response = (HttpWebResponse)request.GetResponse();
  302.  
  303. if (cookieContainer != null)
  304. {
  305. response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
  306. }
  307.  
  308. using (Stream responseStream = response.GetResponseStream())
  309. {
  310. using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8")))
  311. {
  312. string retString = myStreamReader.ReadToEnd();
  313. return retString;
  314. }
  315. }
  316. }
  317. catch (Exception ex)
  318. {
  319. return "";
  320. }
  321. finally
  322. {
  323. if (response != null)
  324. {
  325. response.Close();
  326. response = null;
  327. }
  328. if (request != null)
  329. {
  330. request.Abort();
  331. }
  332. }
  333.  
  334. }
  335.  
  336. ///
  337. /// 请求是否发起自微信客户端的浏览器
  338. ///
  339.  
  340. ///
  341. ///
  342. public static bool IsWeixinClientRequest(this HttpContext httpContext)
  343. {
  344. return !string.IsNullOrEmpty(httpContext.Request.UserAgent) &&
  345. httpContext.Request.UserAgent.Contains("MicroMessenger");
  346. }
  347.  
  348. ///
  349. /// 组装QueryString的方法
  350. /// 参数之间用&连接,首位没有符号,如:a=1&b=2&c=3
  351. ///
  352.  
  353. ///
  354. ///
  355. public static string GetQueryString(this Dictionary formData)
  356. {
  357. if (formData == null || formData.Count == 0)
  358. {
  359. return "";
  360. }
  361.  
  362. StringBuilder sb = new StringBuilder();
  363.  
  364. var i = 0;
  365. foreach (var kv in formData)
  366. {
  367. i++;
  368. sb.AppendFormat("{0}={1}", kv.Key, kv.Value);
  369. if (i < formData.Count)
  370. {
  371. sb.Append("&");
  372. }
  373. }
  374.  
  375. return sb.ToString();
  376. }
  377.  
  378. ///
  379. /// 封装System.Web.HttpUtility.HtmlEncode
  380. ///
  381.  
  382. ///
  383. ///
  384. public static string HtmlEncode(this string html)
  385. {
  386. return System.Web.HttpUtility.HtmlEncode(html);
  387. }
  388. ///
  389. /// 封装System.Web.HttpUtility.HtmlDecode
  390. ///
  391.  
  392. ///
  393. ///
  394. public static string HtmlDecode(this string html)
  395. {
  396. return System.Web.HttpUtility.HtmlDecode(html);
  397. }
  398. ///
  399. /// 封装System.Web.HttpUtility.UrlEncode
  400. ///
  401.  
  402. ///
  403. ///
  404. public static string UrlEncode(this string url)
  405. {
  406. return System.Web.HttpUtility.UrlEncode(url);
  407. }
  408. ///
  409. /// 封装System.Web.HttpUtility.UrlDecode
  410. ///
  411.  
  412. ///
  413. ///
  414. public static string UrlDecode(this string url)
  415. {
  416. return System.Web.HttpUtility.UrlDecode(url);
  417. }
  418. }
  419. public class AsyncRequestUtility
  420. {
  421. public Action OnPostSuccess { get; set; }
  422. public void HttpPost(string url, CookieContainer cookieContainer = null, Dictionary formData = null, Encoding encoding = null)
  423. {
  424. HttpPost(url, cookieContainer, formData, encoding, 12000);
  425. }
  426. public void HttpPost(string url, CookieContainer cookieContainer = null, Dictionary formData = null, Encoding encoding = null, int timeout = 20)
  427. {
  428. string dataString = GetQueryString(formData);
  429. var formDataBytes = formData == null ? new byte[0] : Encoding.UTF8.GetBytes(dataString);
  430. using (MemoryStream ms = new MemoryStream())
  431. {
  432. ms.Write(formDataBytes, 0, formDataBytes.Length);
  433. ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
  434. HttpPost(url, cookieContainer, ms, false, encoding, timeout);
  435. }
  436. }
  437. ///
  438. /// 使用Post方法获取字符串结果
  439. ///
  440.  
  441. ///
  442. ///
  443. public void HttpPost(string url, CookieContainer cookieContainer = null, string fileName = null, Encoding encoding = null)
  444. {
  445. //读取文件
  446. FileStream fileStream = null;
  447. if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
  448. {
  449. fileStream = new FileStream(fileName, FileMode.Open);
  450. }
  451. HttpPost(url, cookieContainer, fileStream, true, encoding);
  452. }
  453. public void HttpPost(string url, CookieContainer cookieContainer = null, Stream postStream = null, bool isFile = false, Encoding encoding = null, int timeout = 1200000)
  454. {
  455. ServicePointManager.DefaultConnectionLimit = 200;
  456. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  457. request.Method = "POST";
  458. request.ContentType = "application/x-www-form-urlencoded";
  459. request.ContentLength = postStream != null ? postStream.Length : 0;
  460. request.Timeout = timeout;
  461. if (cookieContainer != null)
  462. {
  463. request.CookieContainer = cookieContainer;
  464. }
  465. if (postStream != null)
  466. {
  467. //postStream.Position = 0;
  468.  
  469. //上传文件流
  470. Stream requestStream = request.GetRequestStream();
  471.  
  472. byte[] buffer = new byte[1024];
  473. int bytesRead = 0;
  474. while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
  475. {
  476. requestStream.Write(buffer, 0, bytesRead);
  477. }
  478.  
  479. postStream.Close();//关闭文件访问
  480. }
  481. request.BeginGetResponse(new AsyncCallback(this.ResponseCallback), request);
  482. }
  483. private void ResponseCallback(IAsyncResult ar)
  484. {
  485. HttpWebRequest req = (HttpWebRequest)ar.AsyncState; ;
  486. HttpWebResponse resp = null;
  487. try
  488. {
  489. resp = (HttpWebResponse)req.EndGetResponse(ar);
  490. string content = "";
  491. using (Stream responseStream = resp.GetResponseStream())
  492. {
  493. using (StreamReader sr = new StreamReader(responseStream, Encoding.UTF8))
  494. {
  495. content = sr.ReadToEnd();
  496. }
  497. }
  498.  
  499. if (OnPostSuccess != null)
  500. {
  501. OnPostSuccess(content);
  502. }
  503.  
  504. }
  505. finally
  506. {
  507. if (resp != null)
  508. {
  509. resp.Close();
  510. resp.Dispose();
  511. }
  512. req.Abort();
  513. }
  514.  
  515. }
  516. private string GetQueryString(Dictionary formData)
  517. {
  518. if (formData == null || formData.Count == 0)
  519. {
  520. return "";
  521. }
  522.  
  523. StringBuilder sb = new StringBuilder();
  524.  
  525. var i = 0;
  526. foreach (var kv in formData)
  527. {
  528. i++;
  529. sb.AppendFormat("{0}={1}", kv.Key, kv.Value);
  530. if (i < formData.Count)
  531. {
  532. sb.Append("&");
  533. }
  534. }
  535.  
  536. return sb.ToString();
  537. }
  538. }
  539. }

Http请求帮助类的更多相关文章

  1. WebUtils-网络请求工具类

    网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...

  2. Http、Https请求工具类

    最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...

  3. 微信https请求工具类

    工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...

  4. HTTP请求工具类

    HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...

  5. Java请求参数类QueryParameter

    import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; /** * 请求 ...

  6. 实现一个简单的http请求工具类

    OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...

  7. 远程Get,Post请求工具类

    1.远程请求工具类   import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...

  8. C#实现的UDP收发请求工具类实例

    本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...

  9. ajax请求工具类

    ajax的get和post请求工具类: /** * 公共方法类 *  * 使用  变量名=function()定义函数时,如果在变量名前加var,则这个变量变成局部变量 */var Common = ...

  10. 【原创】标准HTTP请求工具类

    以下是个人在项目开发过程中,总结的Http请求工具类,主要包括四种: 1.处理http POST请求[XML格式.无解压]: 2.处理http GET请求[XML格式.无解压]: 3.处理http P ...

随机推荐

  1. SQL SERVER的锁机制(二)——概述(锁的兼容性与可以锁定的资源)

    二.完整的锁兼容性矩阵(见下图) 对上图的是代码说明:见下图. 三.下表列出了数据库引擎可以锁定的资源. 名称 资源 缩写 编码 呈现锁定时,描述该资源的方式 说明 数据行 RID RID 9 文件编 ...

  2. 关于Entity Framework的概念及搭建

    什么是EF? ADO.NET Entity Framework 是一个对象-关系的映射架构. 它支持直接定义完全独立于数据库结构的实体类,并把它们映射到数据库的表和关系上. 三种编程模型: 数据库优先 ...

  3. Download SQL Server Management Studio (SSMS)下载地址

    Download SQL Server Management Studio (SSMS)下载地址: https://msdn.microsoft.com/en-us/library/mt238290. ...

  4. Linux系统文件权限管理(6)

    Linux操作系统是多任务(Multi-tasks)多用户(Multi-users)分时操作系统,linux操作系统的用户就是让我们登录到linux的权限,每当我们使用用户名登录操作系统时,linux ...

  5. Codeforces gym101612 L.Little Difference(枚举+二分)

    传送:http://codeforces.com/gym/101612 题意:给定一个数n(<=1e18),将n分解为若干个数的成绩.要求这些数两两之间的差值不能大于1. 分析: 若n==2^k ...

  6. Weblogic 错误 <BEA-000403> <BEA-000438>解决办法

      控制台提示如下错误: <Error> <Socket> <BEA-000438> <Unable to load performance pack. Us ...

  7. Storm入门示例

    开发Storm的第一步就是设计Topology,为了方便开发者入门,首先我们设计一个简答的例子,该例子的主要的功能就是把每个单词的后面加上Hello,World后缀,然后再打印输出,整个例子的Topo ...

  8. css居中小结

    从css入门就开始接触,无所不在的,一直备受争议的居中问题. css居中分为水平居中和垂直居中,水平居中方式也较为常见和统一,垂直居中的方法就千奇百怪了. 博客原文地址:Claiyre的个人博客 ht ...

  9. Redis---List(链表)

    1. 基本结构 Redis 早期版本存储 list 列表数据结构使用的是压缩列表 ziplist 和普通的双向链表 linkedlist,也就是元素少时用 ziplist,元素多时用 linkedli ...

  10. linux上安装redis4.0.9

    redis安装从3.0的版本到现在4.0的版本,现在装一个4.0的版本供大家学习使用. 先yum安装gcc yum -y install gcc 已加载插件:fastestmirror, langpa ...