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 ...
随机推荐
- AngularJS2 + ASP.NET MVC项目
环境:VS2015, NodeJS:v 6.5, npm: v3.10, AngularJs 2 通过将ASP.NET MVC项目与Angualr 2官网上的quick start整合的过程中遇到些问 ...
- 【原】安装Win7和Ubuntu双系统后,Win7耳机无声音的解决办法
最近安装了Ubuntu的桌面版,作成了双系统,可是发现了一个问题:进入Win7后有时插耳机会没有声音,外放有声音.后来更新驱动也没有解决问题,最后在网上查到了解决办法. 产生原因:进入Ubuntu后, ...
- IOS 开发中 Whose view is not in the window hierarchy 错误的解决办法
在 IOS 开发当中经常碰到 whose view is not in the window hierarchy 的错误,该错误简单的说,是由于 "ViewController" ...
- android知识点随笔
android project中Manifest.xml中的<uses-sdk>标签元素决定的. 此标签包含如下3个属性: android:minSdkVersion —— 此属性决定你的 ...
- Android标题栏上添加多个Menu按钮
最近项目中碰到要在Android Menu旁边再添加一个按钮,而不是点击menu按钮然后在弹出一些选项. MainActivity代码: public class MainActivity exten ...
- 在ASP.NET Web API项目中使用Hangfire实现后台任务处理
当前项目中有这样一个需求:由前端用户的一个操作,需要触发到不同设备的消息推送.由于推送这个具体功能,我们采用了第三方的服务.而这个服务调用有时候可能会有延时,为此,我们希望将消息推送与用户前端操作实现 ...
- geotrellis使用(九)使用geotrellis进行栅格渲染
目录 前言 图像渲染 总结 参考链接 一.前言 前面几篇文章讲解了如何使用Geotrellis进行数据处理.瓦片生成等,今天主要表一下如何使用Geotrellis进行栅格渲染. ...
- 用CSS3动画,让页面动起来
以前就听说过有个库,叫animate.css,但是自己并没有在实际项目中使用过,这次正好要做个招聘页面,得以利用一下这个库,在经常会卡顿的UC浏览器中也能流畅执行. 扫描下面的二维码,可以看到在线的d ...
- 相克军_Oracle体系_随堂笔记003-体系概述
1.进程结构图 对Oracle生产库来讲,服务器进程(可以简单理解是前台进程)的数量远远大于后台进程.因为一个用户进程对应了一个服务器进程. 而且后台进程一般出问题几率不大,所以学习重点也是服务器进程 ...
- java多线程--定时器Timer的使用
定时的功能我们在手机上见得比较多,比如定时清理垃圾,闹钟,等等.定时功能在java中主要使用的就是Timer对象,他在内部使用的就是多线程的技术. Time类主要负责完成定时计划任务的功能,就是在指定 ...