Http请求帮助类
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Text;
- using System.Threading.Tasks;
- using System.Web;
- namespace Nop.Core.Utils
- {
- public static class RequestUtility
- {
- ///
/// 使用Get方法获取字符串结果(暂时没有加入Cookie) /// - ///
- ///
- public static string HttpGet(string url, Encoding encoding = null)
- {
- WebClient wc = new WebClient();
- wc.Encoding = encoding ?? Encoding.UTF8;
- //if (encoding != null)
- //{
- // wc.Encoding = encoding;
- //}
- return wc.DownloadString(url);
- }
- public static dynamic HttpGet(string url)
- {
- HttpClient client = new HttpClient();
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- var response = client.GetAsync(url).Result;
- //result返回值
- string result = response.Content.ReadAsStringAsync().Result;
- return result;
- }
- ///
/// Post数据 /// - /// 模型
- /// server uri
- /// 数据模型
- ///
- public static string Put(string requestUri, T model, IDictionary parameters = null)
- {
- HttpClient client = new HttpClient();
- if (parameters != null && parameters.Count > 0)
- {
- foreach (var item in parameters)
- {
- client.DefaultRequestHeaders.Add(item.Key, item.Value);
- }
- }
- HttpResponseMessage message = client.PutAsJsonAsync(requestUri, model).Result;
- if (message.IsSuccessStatusCode)
- {
- return message.Content.ReadAsStringAsync().Result;
- }
- return null;
- }
- ///
/// 使用Get方法获取字符串结果(暂时没有加入Cookie),parameters字典里面东西会通过循环在request.Headers中添加 /// - ///
- ///
- public static string HttpGet(string url, IDictionary parameters = null, Encoding encoding = null)
- {
- Encoding readCoding = encoding ?? Encoding.UTF8;
- Uri requestUri = new Uri(url);
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
- request.UserAgent = "mozilla/4.0 (compatible; msie 6.0; windows 2000)";
- request.Method = "Get";
- request.ContentType = "application/x-www-form-urlencoded";
- if (parameters != null && parameters.Count > 0)
- {
- foreach (var item in parameters)
- {
- request.Headers.Add(item.Key, item.Value);
- }
- }
- HttpWebResponse response = null;
- try
- {
- try
- {
- response = (HttpWebResponse)request.GetResponse();
- }
- catch (WebException ex)
- {
- //若是远程服务器抛出了异常,则捕获并解析
- response = (HttpWebResponse)ex.Response;
- }
- using (StreamReader sr = new StreamReader(response.GetResponseStream(), readCoding))
- {
- string content = sr.ReadToEnd();
- return content;
- }
- }
- finally
- {
- //释放请求的资源
- if (response != null)
- {
- response.Close();
- response = null;
- }
- if (request != null)
- {
- request.Abort();
- }
- }
- }
- ///
/// /// - ///
- /// 例如Encoding.UTF8.GetBytes(json.Serialize(new { email = "123456@qq.com", password = "111111" }))
- /// 字典里面东西会通过循环在request.Headers中添加
- ///
- ///
- public static string HttpPost(string url, byte[] postStream, IDictionary parameters = null, Encoding encoding = null)
- {
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- request.ProtocolVersion = HttpVersion.Version11;
- request.Method = "POST";
- if (parameters != null && parameters.Count > 0)
- {
- foreach (var item in parameters)
- {
- request.Headers.Add(item.Key, item.Value);
- }
- }
- request.ContentType = "application/json;charset=utf-8";
- request.Accept = "application/json";
- request.Timeout = 60 * 2 * 1000; // 同步接口 调用时间2分钟
- request.ServicePoint.Expect100Continue = false;
- HttpWebResponse response = null;
- try
- {
- postStream = postStream ?? new byte[] { };
- request.ContentLength = postStream.Length;
- var requestStream = request.GetRequestStream();
- requestStream.Write(postStream, 0, postStream.Length);
- requestStream.Close();
- response = (HttpWebResponse)request.GetResponse();
- using (var responseStream = response.GetResponseStream())
- {
- if (responseStream != null)
- {
- using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8))
- {
- return myStreamReader.ReadToEnd();
- }
- }
- }
- }
- catch (Exception ex)
- {
- }
- finally
- {
- if (response != null)
- {
- response.Close();
- }
- request.Abort();
- }
- return "";
- }
- ///
/// Post数据 /// - /// 模型
- /// server uri
- /// 数据模型
- ///
- public static string Post(string requestUri, T model, IDictionary parameters = null)
- {
- HttpClient client = new HttpClient();
- if (parameters != null && parameters.Count > 0)
- {
- foreach (var item in parameters)
- {
- client.DefaultRequestHeaders.Add(item.Key, item.Value);
- }
- }
- HttpResponseMessage message = client.PostAsJsonAsync(requestUri, model).Result;
- if (message.IsSuccessStatusCode)
- {
- return message.Content.ReadAsStringAsync().Result;
- }
- return null;
- }
- ///
/// 使用Post方法获取字符串结果 /// - ///
- public static string HttpPost(string url, CookieContainer cookieContainer = null, Dictionary formData = null, Encoding encoding = null)
- {
- return HttpPost(url, cookieContainer, formData, encoding, 12000);
- }
- public static string HttpPost(string url, CookieContainer cookieContainer = null, Dictionary formData = null, Encoding encoding = null, int timeout = 20)
- {
- string dataString = GetQueryString(formData);
- var formDataBytes = formData == null ? new byte[0] : (encoding == null ? Encoding.UTF8.GetBytes(dataString) : encoding.GetBytes(dataString));
- using (MemoryStream ms = new MemoryStream())
- {
- ms.Write(formDataBytes, 0, formDataBytes.Length);
- ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
- string ret = HttpPost(url, cookieContainer, ms, false, encoding, timeout);
- return ret;
- }
- }
- ///
/// 使用Post方法获取字符串结果 /// - ///
- ///
- public static string HttpPost(string url, CookieContainer cookieContainer = null, string fileName = null, Encoding encoding = null)
- {
- //读取文件
- FileStream fileStream = null;
- if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
- {
- fileStream = new FileStream(fileName, FileMode.Open);
- }
- return HttpPost(url, cookieContainer, fileStream, true, encoding);
- }
- ///
/// 使用Post方法获取字符串结果 /// - ///
- ///
- ///
- /// postStreams是否是文件流
- ///
- public static string HttpPost(string url, CookieContainer cookieContainer = null, Stream postStream = null, bool isFile = false, Encoding encoding = null, int timeout = 1200000)
- {
- ServicePointManager.DefaultConnectionLimit = 200;
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded";
- request.ContentLength = postStream != null ? postStream.Length : 0;
- request.Timeout = timeout;
- if (cookieContainer != null)
- {
- request.CookieContainer = cookieContainer;
- }
- if (postStream != null)
- {
- //postStream.Position = 0;
- //上传文件流
- Stream requestStream = request.GetRequestStream();
- byte[] buffer = new byte[1024];
- int bytesRead = 0;
- while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
- {
- requestStream.Write(buffer, 0, bytesRead);
- }
- postStream.Close();//关闭文件访问
- }
- HttpWebResponse response = null;
- try
- {
- response = (HttpWebResponse)request.GetResponse();
- if (cookieContainer != null)
- {
- response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
- }
- using (Stream responseStream = response.GetResponseStream())
- {
- using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8")))
- {
- string retString = myStreamReader.ReadToEnd();
- return retString;
- }
- }
- }
- catch (Exception ex)
- {
- return "";
- }
- finally
- {
- if (response != null)
- {
- response.Close();
- response = null;
- }
- if (request != null)
- {
- request.Abort();
- }
- }
- }
- ///
/// 请求是否发起自微信客户端的浏览器 /// - ///
- ///
- public static bool IsWeixinClientRequest(this HttpContext httpContext)
- {
- return !string.IsNullOrEmpty(httpContext.Request.UserAgent) &&
- httpContext.Request.UserAgent.Contains("MicroMessenger");
- }
- ///
/// 组装QueryString的方法 /// 参数之间用&连接,首位没有符号,如:a=1&b=2&c=3 /// - ///
- ///
- public static string GetQueryString(this Dictionary formData)
- {
- if (formData == null || formData.Count == 0)
- {
- return "";
- }
- StringBuilder sb = new StringBuilder();
- var i = 0;
- foreach (var kv in formData)
- {
- i++;
- sb.AppendFormat("{0}={1}", kv.Key, kv.Value);
- if (i < formData.Count)
- {
- sb.Append("&");
- }
- }
- return sb.ToString();
- }
- ///
/// 封装System.Web.HttpUtility.HtmlEncode /// - ///
- ///
- public static string HtmlEncode(this string html)
- {
- return System.Web.HttpUtility.HtmlEncode(html);
- }
- ///
/// 封装System.Web.HttpUtility.HtmlDecode /// - ///
- ///
- public static string HtmlDecode(this string html)
- {
- return System.Web.HttpUtility.HtmlDecode(html);
- }
- ///
/// 封装System.Web.HttpUtility.UrlEncode /// - ///
- ///
- public static string UrlEncode(this string url)
- {
- return System.Web.HttpUtility.UrlEncode(url);
- }
- ///
/// 封装System.Web.HttpUtility.UrlDecode /// - ///
- ///
- public static string UrlDecode(this string url)
- {
- return System.Web.HttpUtility.UrlDecode(url);
- }
- }
- public class AsyncRequestUtility
- {
- public Action OnPostSuccess { get; set; }
- public void HttpPost(string url, CookieContainer cookieContainer = null, Dictionary formData = null, Encoding encoding = null)
- {
- HttpPost(url, cookieContainer, formData, encoding, 12000);
- }
- public void HttpPost(string url, CookieContainer cookieContainer = null, Dictionary formData = null, Encoding encoding = null, int timeout = 20)
- {
- string dataString = GetQueryString(formData);
- var formDataBytes = formData == null ? new byte[0] : Encoding.UTF8.GetBytes(dataString);
- using (MemoryStream ms = new MemoryStream())
- {
- ms.Write(formDataBytes, 0, formDataBytes.Length);
- ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
- HttpPost(url, cookieContainer, ms, false, encoding, timeout);
- }
- }
- ///
/// 使用Post方法获取字符串结果 /// - ///
- ///
- public void HttpPost(string url, CookieContainer cookieContainer = null, string fileName = null, Encoding encoding = null)
- {
- //读取文件
- FileStream fileStream = null;
- if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
- {
- fileStream = new FileStream(fileName, FileMode.Open);
- }
- HttpPost(url, cookieContainer, fileStream, true, encoding);
- }
- public void HttpPost(string url, CookieContainer cookieContainer = null, Stream postStream = null, bool isFile = false, Encoding encoding = null, int timeout = 1200000)
- {
- ServicePointManager.DefaultConnectionLimit = 200;
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded";
- request.ContentLength = postStream != null ? postStream.Length : 0;
- request.Timeout = timeout;
- if (cookieContainer != null)
- {
- request.CookieContainer = cookieContainer;
- }
- if (postStream != null)
- {
- //postStream.Position = 0;
- //上传文件流
- Stream requestStream = request.GetRequestStream();
- byte[] buffer = new byte[1024];
- int bytesRead = 0;
- while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
- {
- requestStream.Write(buffer, 0, bytesRead);
- }
- postStream.Close();//关闭文件访问
- }
- request.BeginGetResponse(new AsyncCallback(this.ResponseCallback), request);
- }
- private void ResponseCallback(IAsyncResult ar)
- {
- HttpWebRequest req = (HttpWebRequest)ar.AsyncState; ;
- HttpWebResponse resp = null;
- try
- {
- resp = (HttpWebResponse)req.EndGetResponse(ar);
- string content = "";
- using (Stream responseStream = resp.GetResponseStream())
- {
- using (StreamReader sr = new StreamReader(responseStream, Encoding.UTF8))
- {
- content = sr.ReadToEnd();
- }
- }
- if (OnPostSuccess != null)
- {
- OnPostSuccess(content);
- }
- }
- finally
- {
- if (resp != null)
- {
- resp.Close();
- resp.Dispose();
- }
- req.Abort();
- }
- }
- private string GetQueryString(Dictionary formData)
- {
- if (formData == null || formData.Count == 0)
- {
- return "";
- }
- StringBuilder sb = new StringBuilder();
- var i = 0;
- foreach (var kv in formData)
- {
- i++;
- sb.AppendFormat("{0}={1}", kv.Key, kv.Value);
- if (i < formData.Count)
- {
- sb.Append("&");
- }
- }
- return sb.ToString();
- }
- }
- }
Http请求帮助类的更多相关文章
- WebUtils-网络请求工具类
网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...
- Http、Https请求工具类
最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...
- 微信https请求工具类
工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...
- HTTP请求工具类
HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...
- Java请求参数类QueryParameter
import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; /** * 请求 ...
- 实现一个简单的http请求工具类
OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...
- 远程Get,Post请求工具类
1.远程请求工具类 import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...
- C#实现的UDP收发请求工具类实例
本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...
- ajax请求工具类
ajax的get和post请求工具类: /** * 公共方法类 * * 使用 变量名=function()定义函数时,如果在变量名前加var,则这个变量变成局部变量 */var Common = ...
- 【原创】标准HTTP请求工具类
以下是个人在项目开发过程中,总结的Http请求工具类,主要包括四种: 1.处理http POST请求[XML格式.无解压]: 2.处理http GET请求[XML格式.无解压]: 3.处理http P ...
随机推荐
- SQL SERVER的锁机制(二)——概述(锁的兼容性与可以锁定的资源)
二.完整的锁兼容性矩阵(见下图) 对上图的是代码说明:见下图. 三.下表列出了数据库引擎可以锁定的资源. 名称 资源 缩写 编码 呈现锁定时,描述该资源的方式 说明 数据行 RID RID 9 文件编 ...
- 关于Entity Framework的概念及搭建
什么是EF? ADO.NET Entity Framework 是一个对象-关系的映射架构. 它支持直接定义完全独立于数据库结构的实体类,并把它们映射到数据库的表和关系上. 三种编程模型: 数据库优先 ...
- Download SQL Server Management Studio (SSMS)下载地址
Download SQL Server Management Studio (SSMS)下载地址: https://msdn.microsoft.com/en-us/library/mt238290. ...
- Linux系统文件权限管理(6)
Linux操作系统是多任务(Multi-tasks)多用户(Multi-users)分时操作系统,linux操作系统的用户就是让我们登录到linux的权限,每当我们使用用户名登录操作系统时,linux ...
- Codeforces gym101612 L.Little Difference(枚举+二分)
传送:http://codeforces.com/gym/101612 题意:给定一个数n(<=1e18),将n分解为若干个数的成绩.要求这些数两两之间的差值不能大于1. 分析: 若n==2^k ...
- Weblogic 错误 <BEA-000403> <BEA-000438>解决办法
控制台提示如下错误: <Error> <Socket> <BEA-000438> <Unable to load performance pack. Us ...
- Storm入门示例
开发Storm的第一步就是设计Topology,为了方便开发者入门,首先我们设计一个简答的例子,该例子的主要的功能就是把每个单词的后面加上Hello,World后缀,然后再打印输出,整个例子的Topo ...
- css居中小结
从css入门就开始接触,无所不在的,一直备受争议的居中问题. css居中分为水平居中和垂直居中,水平居中方式也较为常见和统一,垂直居中的方法就千奇百怪了. 博客原文地址:Claiyre的个人博客 ht ...
- Redis---List(链表)
1. 基本结构 Redis 早期版本存储 list 列表数据结构使用的是压缩列表 ziplist 和普通的双向链表 linkedlist,也就是元素少时用 ziplist,元素多时用 linkedli ...
- linux上安装redis4.0.9
redis安装从3.0的版本到现在4.0的版本,现在装一个4.0的版本供大家学习使用. 先yum安装gcc yum -y install gcc 已加载插件:fastestmirror, langpa ...