/// <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. ASP.NET MVC 5– 使用Wijmo MVC 5模板1分钟创建应用

    开始使用 使用ComponentOne Studio for ASP.NET Wijmo制作MVC5应用程序,首先要做的是安装Studio for ASP.NET Wijmo . 测试环境 VS201 ...

  2. Vue 入门指南

    英文:http://vuejs.org/guide/index.html 介绍 vue.js 是用来构建web应用接口的一个库 技术上,Vue.js 重点集中在MVVM模式的ViewModel层,它连 ...

  3. 使用Emit把Datatable转换为对象集合(List<T>)

    Emit生成动态方法部分摘自网上,但是经过修改,加入了对委托的缓存以及类结构的调整,使之调用更简洁方便.大致的思路是:要实现转换datatable到某个指定对象的集合,本质是实现转换一个datarow ...

  4. Atitit事件代理机制原理 基于css class的事件代理

    Atitit事件代理机制原理 基于css class的事件代理 1.1. 在javasript中delegate这个词经常出现,看字面的意思,代理.委托1 1.2. 事件代理1 1.3. 代理标准化规 ...

  5. HTML5入门以及新标签

    HTML5 学习总结(一)--HTML5入门与新增标签   目录 一.HTML5概要 1.1.为什么需要HTML5 1.2.什么是HTML5 1.3.HTML5现状及浏览器支持 1.4.HTML5特性 ...

  6. 异步方法不能使用ref和out的解决方法

    异常处理汇总-后端系列:http://www.cnblogs.com/dunitian/p/4523006.html 应用场景==>后端现在都是用异步方法,那么分页是必不可少的,于是就有了这个问 ...

  7. jQuery插件:jqGrid使用(一)

    1. Loading Data Load from JavaScript Array BundleConfig.cs using System.Web; using System.Web.Optimi ...

  8. 深入理解脚本化CSS系列第一篇——脚本化行内样式

    × 目录 [1]用法 [2]属性 [3]方法 前面的话 脚本化CSS,通俗点说,就是使用javascript来操作CSS.引入CSS有3种方式:外部样式,内部样式和行间样式.本文将主要介绍脚本化行间样 ...

  9. 基于Fragment的百度地图框架的使用

    博客:http://blog.csdn.net/developer_jiangqq (一)基本介绍(Fragment和SupportMapFragment): Fragment的使用现在安卓APP开发 ...

  10. ASP.NET WebAPi之断点续传下载(中)

    前言 前情回顾:上一篇我们遗留了两个问题,一个是未完全实现断点续传,另外则是在响应时是返回StreamContent还是PushStreamContent呢?这一节我们重点来解决这两个问题,同时就在此 ...