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(); } } }
本人在长沙, 有工作可以加我QQ4658276