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请求帮助类的更多相关文章

  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. delphi控制 word的几种方法--转

    对几种方法的难易程度的判别 a.通过Delphi的控件TOleContainer 将Word嵌入 这是最简单的Ole嵌入,能够直接将Word文档调用,只需要使用ToleContainer.Run就可以 ...

  2. cxGrid之checkbox小结

    http://www.cnblogs.com/Kim53622744/p/4428997.html 在cxgrid中增加选择列 1.在dataset(query/table/clientdataset ...

  3. devexpress gridview 添加按钮

    #region 添加按钮事件 private RepositoryItemButtonEdit CreateRepositoryItemButtonEdit(Dictionary<object, ...

  4. wpf Im

  5. C# EPPlus导出EXCEL,并生成Chart表

    一  在negut添加EPPlus.dll库文件. 之前有写过直接只用Microsoft.Office.Interop.Excel 导出EXCEL,并生成Chart表,非常耗时,所以找了个EPPlus ...

  6. 清理MVC4 Internaet 项目模板清理

    新建项目时选择空的MVC项目 是没有Bundle 引用的非常痛苦,但是如果选择Internet模板 MVC4的模板会帮你添加一堆的JQuery 引用  打开NuGet Console 执行以下指令能帮 ...

  7. 【SPOJ10707】 COT2 Count on a tree II

    SPOJ10707 COT2 Count on a tree II Solution 我会强制在线版本! Solution戳这里 代码实现 #include<stdio.h> #inclu ...

  8. Flask系列10-- Flask请求上下文源码分析

    总览 一.基础准备. 1. local类 对于一个类,实例化得到它的对象后,如果开启多个线程对它的属性进行操作,会发现数据时不安全的 import time from threading import ...

  9. 我的AI之路 —— 从裸机搭建GPU版本的深度学习环境

    之前一直在CPU上跑深度学习,由于做的是NLP方向所以也能勉强忍受.最近在做图像的时候,实在是扛不住了...还好领导们的支持买个虚拟机先体验下.由于刚买的机器,环境都得自己摸索,瞎搞过很多次,也走过很 ...

  10. js获取当前页面相关信息

    1. 获取整个url: console.log(window.location.href)  http://localhost:8082/Index.html?name=tom 2. 获取域名加端口号 ...