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 ...
随机推荐
- HTML超级链接详细讲解
超级链接是网站中使用比较频繁的HTML元素,因为网站的各种页面都是由超级链接串接而成,超级链接完成了页面之间的跳转.超级链接是浏览者和服务器的交互的主要手段,在后面的技术中会逐步深化学习. — 注意 ...
- SQL Server主要系统视图说明
SELECT * FROM sys.all_columns --显示属于用户定义对象和系统对象的所有列的联合--https://docs.microsoft.com/zh-cn/sql/relatio ...
- WPF自定义Window窗体样式
资源文件代码: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation ...
- 为什么主流的 App 看起来都差不多?这可能是件好事
欢迎访问网易云社区,了解更多网易技术产品运营经验. 现在设计师可以把精力都花在真正有意义的地方了. 打开Instagram.Airbnb.Apple Music.Twitter.Dropbox或Lyf ...
- 企业项目开发--cookie(3)
此文已由作者赵计刚授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 2.2.3.AdminController 1 package com.xxx.web.admin; ...
- docker容器备份、恢复和迁移volume方案
volume作为数据的载体,在很多情况下需要对其中的数据进行备份.迁移或是恢复.下面一docker容器的volume为例,说一下备份的技巧. 我们先建立一个容器vol_simple,该容器在/date ...
- Synchronzied与ReentrantLock
- EF 通过修改模版 更改生成实体名称
直接修改T4 模版中对应关系就可以了,我这里是去掉了表中的“_”
- SQLAlchemy介绍和基本使用
pymysql:pymysql是用Python来操作mysql的包,因此通过pip来安装,命令如下:pip3 install pymysql.如果您用的是Python 3,请安装pymysql 豆瓣源 ...
- Googel 浏览器 模拟发送请求工具--Advanced REST Client
Advanced REST Client是 Chrome 浏览器下的一个插件,通过它可以发送 http.https.WebSocket 请求.在 Chrome 商店下搜索 Advanced REST ...