/// <summary>
/// 有关HTTP请求的辅助类
/// </summary>
public class HttpQuery
{
private static readonly string DefaultUserAgent =
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; public static void Get(string url, object data, Action<string> callback)
{
IDictionary<string, string> parameters = Getparameters(data); if (!(parameters == null || parameters.Count == ))
{
url += "?";
foreach (var item in parameters)
{
url += item.Key + "=" + item.Value + "&";
}
}
CreateGetHttpResponse(url, null, null, null, callback);
} public static void Post(string url, object data, Action<string> callback)
{
IDictionary<string, string> parameters = Getparameters(data); CreatePostHttpResponse(url, parameters, null, null, Encoding.UTF8, null, callback);
} public static void Post(string url, string data, Action<string> callback)
{
CreatePostHttpResponse(url, data, null, null, Encoding.UTF8, null, callback);
} private static IDictionary<string, string> Getparameters(object data)
{
if (data == null)
{
return new Dictionary<string, string>();
}
IDictionary<string, string> parameters = new Dictionary<string, string>(); Type type = data.GetType();
PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo p in props)
{
parameters.Add(p.Name, p.GetValue(data).ToString());
} return parameters;
} /// <summary>
/// 创建GET方式的HTTP请求
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="timeout">请求的超时时间</param>
/// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
/// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
/// <returns></returns>
private static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent,
CookieCollection cookies, Action<string> callback, string encoding = "utf-8")
{
if (string.IsNullOrEmpty(url))
{
return null;
//throw new ArgumentNullException("url");
}
try
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.UserAgent = DefaultUserAgent;
if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
} HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse; StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(),
System.Text.Encoding.GetEncoding(encoding)); string html = "";
//获取请求到的数据
html = reader.ReadToEnd();
//关闭
httpWebResponse.Close();
reader.Close(); Regex regex = new Regex("charset=(?<code>\\w+)\"");
Match match = regex.Match(html);
string code = match.Groups["code"].Value;
if (!string.IsNullOrWhiteSpace(code) && code.ToLower() != encoding.ToLower())
{
return CreateGetHttpResponse(url, timeout, userAgent, cookies, callback, code);
}
else
{
callback(html);
return httpWebResponse;
}
}
catch
{
callback(null);
}
return null;
} /// <summary>
/// 创建POST方式的HTTP请求
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="parameters">随同请求POST的参数名称及参数值字典</param>
/// <param name="timeout">请求的超时时间</param>
/// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
/// <param name="requestEncoding">发送HTTP请求时所用的编码</param>
/// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
/// <returns></returns>
private static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters,
int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies, Action<string> callback)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
if (requestEncoding == null)
{
throw new ArgumentNullException("requestEncoding");
}
HttpWebRequest request = null;
try
{
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded"; if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
else
{
request.UserAgent = DefaultUserAgent;
} if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
//如果需要POST数据
if (!(parameters == null || parameters.Count == ))
{
StringBuilder buffer = new StringBuilder();
int i = ;
foreach (string key in parameters.Keys)
{
if (i > )
{
buffer.AppendFormat("&{0}={1}", key, parameters[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, parameters[key]);
}
i++;
}
byte[] data = requestEncoding.GetBytes(buffer.ToString());
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, , data.Length);
}
} HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse; StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(),
System.Text.Encoding.GetEncoding("utf-8")); string html = "";
//获取请求到的数据
html = reader.ReadToEnd(); //关闭
httpWebResponse.Close();
reader.Close(); callback(html); return httpWebResponse;
}
catch
{
callback(null);
}
return null;
} private static HttpWebResponse CreatePostHttpResponse(string url, string parameters, int? timeout,
string userAgent, Encoding requestEncoding, CookieCollection cookies, Action<string> callback)
{
if (string.IsNullOrEmpty(url))
{
return null;
//throw new ArgumentNullException("url");
}
if (requestEncoding == null)
{
throw new ArgumentNullException("requestEncoding");
}
HttpWebRequest request = null;
try
{
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded"; if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
else
{
request.UserAgent = DefaultUserAgent;
} if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
//如果需要POST数据
if (!string.IsNullOrEmpty(parameters))
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(parameters);
streamWriter.Flush();
}
} HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse; StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(),
System.Text.Encoding.GetEncoding("utf-8")); string html = "";
//获取请求到的数据
html = reader.ReadToEnd(); //关闭
httpWebResponse.Close();
reader.Close(); callback(html); return httpWebResponse;
}
catch
{
callback(null);
}
return null;
} private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain,
SslPolicyErrors errors)
{
return true; //总是接受
} }

使用方法

HttpQuery.Post(url, new { key = key, xmlCount = xmlCount }, (msg) =>
{ });

ahjesus HttpQuery的更多相关文章

  1. ahjesus在asp.net中还可以通过设置HttpCookie对象的过期时间为DateTime.MinValue来指定此Cookies为跟随浏览器生效

    ahjesus在asp.net中还可以通过设置HttpCookie对象的过期时间为DateTime.MinValue来指定此Cookies为跟随浏览器生效

  2. ahjesus Axure RP 7.0注册码

    ahjesus Axure RP 7.0注册码 用户名:axureuser 序列号:8wFfIX7a8hHq6yAy6T8zCz5R0NBKeVxo9IKu+kgKh79FL6IyPD6lK7G6+t ...

  3. ahjesus使用T4模板自动维护实体

    在entity项目里新建模板DBEntity.tt <#@ template debug="false" hostspecific="true" lang ...

  4. ahjesus配置vsftpd虚拟用户在Ubuntu

    网上搜索了很多资料,过时,不全,货不对版 已下步骤亲测有效,不包含匿名用户登录 1.新建/home/loguser.txt 并填充内容,格式如下 用户名密码用户名密码用户名密码 2.生成db文件用于用 ...

  5. ahjesus让nodejs支持dotjs模板

    经过几天的实验加搜索,终于知道一个中间件可以解决这个问题了 npm install consolidate consolidate传送门 传送门2使用说明传送门快照:ahjesus Since doT ...

  6. ahjesus 获取当前方法被调用执行的具体位置,包括命名空间和方法

    MethodBase method = ).GetMethod(); string ahjesus = method.ReflectedType.FullName + "." + ...

  7. ahjesus C# Flags 位域略说

    class Program { [Flags] public enum Week { [Description("星期一")] Monday = << , [Descr ...

  8. ahjesus如何在windows下制作适用于mac的u盘启动盘

    先用macdrive把U盘格式化成hfs+格式,然后下载原版dmg格式系统,再用ultraISO将dmg转成ISO格式(也可以不用转换),最后用ultraISO里面“启动”--->“写入硬盘映像 ...

  9. ahjesus Unity3D XML注释被编译的问题

    public class XMLStringReader : MonoBehaviour { public string slectedItem; private bool editing = fal ...

随机推荐

  1. 关于GC和析构函数的一个趣题

    这个有趣的问题感谢装配脑袋友情提供. 请看如下代码: public class Dummy { public static Dummy Instance; ; ~Dummy() { Instance ...

  2. [备忘]检索 COM 类工厂中 CLSID 为 {91493441-5A91-11CF-8700-00AA0060263B} 的组件时失败解决方法

    检索 COM 类工厂中 CLSID 为 {91493441-5A91-11CF-8700-00AA0060263B} 的组件时失败,原因是出现以下错误: 80070005 在CSDN上总是有网友问这个 ...

  3. 我心中的核心组件(可插拔的AOP)~大话开篇及目录

    回到占占推荐博客索引 核心组件 我心中的核心组件,核心组件就是我认为在项目中比较常用的功能,如日志,异常处理,消息,邮件,队列服务,调度,缓存,持久化,分布式文件存储,NoSQL存储,IoC容器,方法 ...

  4. SpringMVC配置项学习笔记

    1. <mvc:annotation-driven /> <mvc:annotation-driven />是一种简写形式,默认会注册DefaultAnnotationHand ...

  5. Java易混淆的概率:成员变量、类变量、实例变量、局部变量

    先看代码 public class Variable{ int b=0; //实例变量 static int a=0; //类变量 final String c="wws"; // ...

  6. 谈谈StringBuffer和StringBuilder

    (1) 速度 在执行速度方面的比较:StringBuilder > StringBuffer > String ①String 是不可变的对象(String类源码中存放字符的数组被声明为f ...

  7. HTML5新增标签与属性

    目录 一.HTML5新增属性 1.1.contextmenu 1.2.contentEditable 1.3.hidden 1.4.draggable 1.5.data-* 1.6.placehold ...

  8. oc集合

    本人之前学习过一年半ios开发 由于行情太过凄惨,故转前端.心在前端,苹果亦难忘!把我平时的笔记作出给大家总结! 回顾之前的知识 便利初始化函数:框架类库中的一些类有一系列的以init开头的方法,这些 ...

  9. 《JS设计模式笔记》 2,简单工厂模式

    <script type="text/javascript"> //简单工厂模式 //定义:由一个方法来决定到底要创建哪个类的实例,而这些实例经常拥有相同的接口.其实例 ...

  10. .NET平台开源项目速览(4).NET文档生成工具ADB及使用

    很久以前就使用ADB这个工具来生成项目的帮助文档.功能强大,在学习一些开源项目的过程中,官方没有提供CHM帮助文档,所以为了快速的了解项目结构和注释.就生成文档来自己看,非常好用.这也是一个学习方法吧 ...