ahjesus HttpQuery
/// <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的更多相关文章
- ahjesus在asp.net中还可以通过设置HttpCookie对象的过期时间为DateTime.MinValue来指定此Cookies为跟随浏览器生效
ahjesus在asp.net中还可以通过设置HttpCookie对象的过期时间为DateTime.MinValue来指定此Cookies为跟随浏览器生效
- ahjesus Axure RP 7.0注册码
ahjesus Axure RP 7.0注册码 用户名:axureuser 序列号:8wFfIX7a8hHq6yAy6T8zCz5R0NBKeVxo9IKu+kgKh79FL6IyPD6lK7G6+t ...
- ahjesus使用T4模板自动维护实体
在entity项目里新建模板DBEntity.tt <#@ template debug="false" hostspecific="true" lang ...
- ahjesus配置vsftpd虚拟用户在Ubuntu
网上搜索了很多资料,过时,不全,货不对版 已下步骤亲测有效,不包含匿名用户登录 1.新建/home/loguser.txt 并填充内容,格式如下 用户名密码用户名密码用户名密码 2.生成db文件用于用 ...
- ahjesus让nodejs支持dotjs模板
经过几天的实验加搜索,终于知道一个中间件可以解决这个问题了 npm install consolidate consolidate传送门 传送门2使用说明传送门快照:ahjesus Since doT ...
- ahjesus 获取当前方法被调用执行的具体位置,包括命名空间和方法
MethodBase method = ).GetMethod(); string ahjesus = method.ReflectedType.FullName + "." + ...
- ahjesus C# Flags 位域略说
class Program { [Flags] public enum Week { [Description("星期一")] Monday = << , [Descr ...
- ahjesus如何在windows下制作适用于mac的u盘启动盘
先用macdrive把U盘格式化成hfs+格式,然后下载原版dmg格式系统,再用ultraISO将dmg转成ISO格式(也可以不用转换),最后用ultraISO里面“启动”--->“写入硬盘映像 ...
- ahjesus Unity3D XML注释被编译的问题
public class XMLStringReader : MonoBehaviour { public string slectedItem; private bool editing = fal ...
随机推荐
- UIColor 使用起来的坑
我们一般会用 UIColor 的RGB来生成颜色: [UIColor colorWithRed:220/255 green:220/255 blue:220/255 alpha:1.0];//这样生成 ...
- 2013 duilib入门简明教程 -- 响应按钮事件(4)
上一个Hello World的教程里有一句代码是这样的:CControlUI *pWnd = new CButtonUI; 也就是说,其实那整块绿色背景区域都是按钮的区域.(这里简要介 ...
- Tornado框架中视图模板Template的使用
上文的程序中有这样一段: class MessageHandler(tornado.web.RequestHandler): def get(self): self.write(''' <htm ...
- Leetcode-83 Remove Duplicates from Sorted List
#83. Remove Duplicates from Sorted List Given a sorted linked list, delete all duplicates such that ...
- XE1:使用SSMS创建Extended Events
Extended Events 用于取代SQL trace,是SQL Server 追踪系统运行的神器,其创建过程十分简单. 一,创建Extended Events的Session step1,打开N ...
- sizzle编译函数
一个人去完成一件事情,如果派多个人去做的话,只要配合默契,效率比一个人做肯定要高,效率提高,所需的时间就减少了.如果只能一个人完成,那么必须设法提高自己的劳动效率,这个提高可以是量的改变也可以是质的改 ...
- Unity3D知识框架
美术部分: 3d模型,材质,纹理,shader,Animator,Animation,天空盒,灯光效果,烘焙 程序部分: 基本组成: ...
- ASP.NET MVC5 网站开发实践(二) Member区域–我的咨询列表及添加咨询
上次把咨询的架构搭好了,现在分两次来完成咨询:1.用户部分,2管理部分.这次实现用户部分,包含两个功能,查看我的咨询和进行咨询. 目录: ASP.NET MVC5 网站开发实践 - 概述 ASP.NE ...
- Android应用中实现系统“分享”接口
在android下各种文件管理器中,我们选择一个文件,点击分享可以看到弹出一些app供我们选择,这个是android系统分享功能,我们做的app也可以出现在这个列表中. 第一步:在Manifest.x ...
- 在非SQL客户端使用命令行方式定期连接SQL Server 服务器并模拟用户查询操作,同时输出信息内容
一个很长的标题,实现的功能就是尽量使用非人力的方式模拟人去做一件事情,为了便于记录,将他们输出成文件方便查阅. 图形界面方式,使用微软自己的ConnMaker.exe,或者Microsoft 数据连接 ...