C# 一个特别不错的http请求类
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions; namespace aaa
{
public class ResponseModel
{
private WebHeaderCollection header;
/// <summary>
/// 返回的头部信息集合
/// </summary>
public WebHeaderCollection Header
{
get { return header; }
set { header = value; }
}
private string html;
/// <summary>
/// 返回的文本内容
/// </summary>
public string Html
{
get { return html; }
set { html = value; }
}
private Stream stream;
/// <summary>
/// 返回的流内容
/// </summary>
public Stream Stream
{
get { return stream; }
set { stream = value; }
} }
public class HttpHelper
{
private string accept = "application/json,text/javascrip{过滤}t,text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
private System.Net.CookieContainer cc = new System.Net.CookieContainer();
private string contentType = "application/x-www-form-urlencoded"; private int timeOut = ;
public NameValueCollection Heads = new NameValueCollection();
private bool AllowAutoRedirect = false;
bool needReset = false;
private System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("utf-8"); public IWebProxy Proxy;
private string[] userAgents = new string[] { "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0" }; private string userAgent
{
get
{
return this.userAgents[new Random().Next(, this.userAgents.Length)];
}
} /// <summary>
/// 设置下一次请求为自动重定向
/// </summary>
/// <param name="value"></param>
public void SetAllowAutoRedirectOneTime(bool value)
{
AllowAutoRedirect = value;
needReset = true;
} /// <summary>
/// 网页访问
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="isPost">是否Post</param>
/// <param name="postData">Post数据内容</param>
/// <param name="retType">返回类型0为文本,1为Stream</param>
/// <param name="cookieContainer">cookie</param>
/// <param name="refurl">Referer</param>
/// <param name="_contentType">contentType</param>
/// <param name="headers">请求头</param>
/// <returns></returns>
public ResponseModel HttpVisit(string url, bool isPost = false, string postData = null, int retType = , System.Net.CookieContainer cookieContainer = null, string refurl = null, string _contentType = null, NameValueCollection headers = null)
{
if (cookieContainer == null)
{
cookieContainer = this.cc;
} if (!isPost)
{
return GetHtml(url, refurl, cookieContainer, _contentType, headers, retType);
} ResponseModel model = new ResponseModel(); ServicePointManager.Expect100Continue = true; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
byte[] bytes = System.Text.Encoding.Default.GetBytes(postData);
request = (HttpWebRequest)WebRequest.Create(url);
if (this.Proxy != null) request.Proxy = this.Proxy;
request.CookieContainer = cookieContainer;
request.Timeout = timeOut;
if (string.IsNullOrEmpty(_contentType))
{
request.ContentType = this.contentType;
}
else
{
request.ContentType = _contentType;
} if (string.IsNullOrEmpty(refurl))
{
request.Referer = url;
}
else
{
request.Referer = refurl;
} request.AllowAutoRedirect = AllowAutoRedirect;
request.Accept = this.accept;
request.UserAgent = this.userAgent; if (headers != null)
{
request.Headers.Add(Heads);
request.Headers.Add(headers);
}
else
{
request.Headers.Add(Heads);
} request.Method = isPost ? "POST" : "GET";
request.ContentLength = bytes.Length; Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, , bytes.Length);
requestStream.Close(); if (retType == )
{
response = (HttpWebResponse)request.GetResponse(); model.Header = response.Headers; Stream responseStream = response.GetResponseStream(); if (response.Cookies.Count > )
{
this.cc.Add(response.Cookies);
} model.Stream = responseStream;
return model; } string str = string.Empty;
response = (HttpWebResponse)request.GetResponse(); model.Header = response.Headers; string encoding = "utf-8"; if (!string.IsNullOrEmpty(response.CharacterSet))
{
encoding = response.CharacterSet.ToLower();
}
else
{
encoding = this.encoding.HeaderName;
} if (response.ContentEncoding.ToLower().Contains("gzip"))
{ using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
{ str = reader.ReadToEnd();
}
}
}
else if (response.ContentEncoding.ToLower().Contains("deflate"))
{
using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
{ str = reader.ReadToEnd();
} }
}
else
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
{ str = reader.ReadToEnd();
}
}
} request.Abort();
response.Close();
request.Abort();
if (response.Cookies.Count > )
{
this.cc.Add(response.Cookies);
}
model.Html = str;
return model;
}
catch (Exception ex)
{
if (request != null) request.Abort();
if (response != null)
{
response.Close(); return new ResponseModel() { Html = ex.Message, Header = response.Headers };
}
return new ResponseModel() { Html = ex.Message };
}
finally
{
if (needReset)
{
AllowAutoRedirect = false;
needReset = false;
}
}
}
/// <summary>
/// 清理string类型Cookie.剔除无用项返回结果为null时遇见错误.
/// </summary>
/// <param name="Cookies"></param>
/// <returns></returns>
public CookieCollection ClearCookie(string Cookies)
{
try
{
CookieCollection cookies = new CookieCollection();
string rStr = string.Empty;
Cookies = Cookies.Replace(";", "; ");
Regex r = new Regex("(?<=,)(?<cookie>[^ ]+=(?!deleted;)[^;]+);");
MatchCollection ms = r.Matches("," + Cookies);
foreach (Match m in ms)
{
string[] cookie = m.Groups["cookie"].Value.Split('='); if (cookie.Length > )
cookies.Add(new Cookie(cookie[], cookie[])); }
return cookies;
}
catch
{
return new CookieCollection();
}
} private ResponseModel GetHtml(string url, string refurl = null, System.Net.CookieContainer cookieContainer = null, string _contentType = "", NameValueCollection headers = null, int retType = )
{
if (cookieContainer == null)
{
cookieContainer = this.cc;
} ResponseModel model = new ResponseModel(); ServicePointManager.Expect100Continue = true; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
if (this.Proxy != null) request.Proxy = this.Proxy;
request.CookieContainer = cookieContainer;
request.Timeout = timeOut;
if (string.IsNullOrEmpty(_contentType))
{
request.ContentType = this.contentType;
}
else
{
request.ContentType = _contentType;
} if (string.IsNullOrEmpty(refurl))
{
request.Referer = url;
}
else
{
request.Referer = refurl;
} request.AllowAutoRedirect = AllowAutoRedirect;
request.Accept = this.accept;
request.UserAgent = this.userAgent; if (headers != null)
{
request.Headers.Add(Heads);
request.Headers.Add(headers);
}
else
{
request.Headers.Add(Heads);
} request.Method = "GET"; if (retType == )
{
response = (HttpWebResponse)request.GetResponse(); model.Header = response.Headers; Stream responseStream = response.GetResponseStream(); if (response.Cookies.Count > )
{
this.cc.Add(response.Cookies);
} model.Stream = responseStream; return model; } string str = string.Empty;
response = (HttpWebResponse)request.GetResponse(); model.Header = response.Headers; string encoding = "utf-8"; if (!string.IsNullOrEmpty(response.CharacterSet))
{
encoding = response.CharacterSet.ToLower();
}
else
{
encoding = this.encoding.HeaderName;
} if (response.ContentEncoding.ToLower().Contains("gzip"))
{ using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
{ str = reader.ReadToEnd();
}
}
}
else if (response.ContentEncoding.ToLower().Contains("deflate"))
{
using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
{ str = reader.ReadToEnd();
} }
}
else
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
{ str = reader.ReadToEnd();
}
}
} if (response.Cookies.Count > )
{
cookieContainer.Add(response.Cookies);
} request.Abort();
response.Close(); model.Html = str;
return model;
}
catch (Exception ex)
{
if (request != null) request.Abort();
if (response != null)
{
response.Close(); return new ResponseModel() { Html = ex.Message, Header = response.Headers };
}
return new ResponseModel() { Html = ex.Message };
}
finally
{
if (needReset)
{
AllowAutoRedirect = false;
needReset = false;
}
}
} private bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
//直接通过HTTPS的证书请求
return true;
} public Stream GetStream(string url)
{
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
if (this.Proxy != null) request.Proxy = this.Proxy;
request.CookieContainer = this.cc;
request.ContentType = this.contentType;
// request.ServicePoint.ConnectionLimit = this.maxTry;
request.Timeout = 0x1388;
request.Referer = url;
request.Accept = this.accept;
request.UserAgent = this.userAgent;
request.Method = "GET";
response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream();
// this.currentTry--;
if (response.Cookies.Count > )
{
this.cc.Add(response.Cookies);
}
return responseStream;
}
catch (Exception ex)
{
// if (this.currentTry <= this.maxTry) this.GetHtml(url, cookieContainer);
// this.currentTry--;
if (request != null) request.Abort();
if (response != null) response.Close();
return null;
}
} #region String与CookieContainer互转
/// <summary>
/// 将String转CookieContainer
/// </summary>
/// <param name="url"></param>
/// <param name="cookie"></param>
/// <returns></returns>
public CookieContainer StringToCookie(string url, string cookie)
{
string[] arrCookie = cookie.Split(';');
CookieContainer cookie_container = new CookieContainer(); //加载Cookie
foreach (string sCookie in arrCookie)
{
if (sCookie.IndexOf("expires") > )
continue;
cookie_container.SetCookies(new Uri(url), sCookie);
}
return cookie_container;
} /// <summary>
/// 将CookieContainer转换为string类型
/// </summary>
/// <param name="cc"></param>
/// <returns></returns>
public string GetCookieString()
{
System.Collections.Generic.List<Cookie> lstCookies = new System.Collections.Generic.List<Cookie>();
Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
StringBuilder sb = new StringBuilder();
foreach (object pathList in table.Values)
{
SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
| System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
foreach (CookieCollection colCookies in lstCookieCol.Values)
foreach (Cookie c in colCookies)
{
sb.Append(c.Name).Append("=").Append(c.Value).Append(";");
}
}
return sb.ToString();
}
#endregion }
}
C# 一个特别不错的http请求类的更多相关文章
- 一个比较强大的HTTP请求类,支持文本参数和文件参数。
一个 http 请求类 ,支持文件上传,从淘宝 top sdk 里面扣出来的,蛮好用的,做个记录而已. 调用代码: Dictionary<string, string> textParas ...
- 一个特别不错的jQuery快捷键插件:js-hotkeys
这其实不是什么新技术,这个插件在很早前就已经发布了,之前有项目用到,所以分享出来添加方式的例子 jQuery.hotkeys.add('esc',function (){ //执行函数 }); jQu ...
- 一个linux下简单的纯C++实现Http请求类(GET,POST,上传,下载)
目录 一个linux下简单的纯C++实现Http请求类(GET,POST,上传,下载) Http协议简述 HttpRequest类设计 请求部分 接收部分 关于上传和下载 Cpp实现 关于源码中的Lo ...
- block传值以及利用block封装一个网络请求类
1.block在俩个UIViewController间传值 近期刚学了几招block 的高级使用方法,事实上就是利用block语法在俩个UIViewController之间传值,在这里分享给刚開始学习 ...
- 用CIL写程序:定义一个叫“慕容小匹夫”的类
前文回顾: <用CIL写程序:你好,沃尔德> <用CIL写程序:写个函数做加法> 前言: 今天是乙未羊年的第一天,小匹夫先在这里给各位看官拜个年了.不知道各位看官是否和匹夫一样 ...
- 【PHPsocket编程专题(实战篇③)】构建基于socket的HTTP请求类
该代码是两年前写的,现在看起来有点渣了,仅仅是提供一个思路,现在做一些Api开发的时候官方会有一些SDK,这些SDK其实原理都是通过socket来通讯的,其实我个人主张用curl更方便,当然前提是你的 ...
- 发送一个简单的http get 请求并且响应
问题 如何发送一个简单的HTTP GET请求并且取回相应的HTTP响应. 设计 创建一个WebClient类的实例,然后使用它的DownloadData()方法. 方案 string uri = &q ...
- WinSock IOCP 模型总结(附一个带缓存池的IOCP类)
前言 本文配套代码:https://github.com/TTGuoying/IOCPServer 由于篇幅原因,本文假设你已经熟悉了利用Socket进行TCP/IP编程的基本原理,并且也熟练的掌握了 ...
- Servlet(五):一个Servlet处理多个请求
一.为什么要使用一个Servlet来处理多个请求? 当浏览器发送了一次请求到服务器时,servlet容器会根据请求的url-pattern找到对应的Servlet类,执行对应的doPost或doGet ...
随机推荐
- Ionic3 新增 Service
service是单例模式的 新增Service类 search.service.ts import {Injectable} from '@angular/core'; @Injectable() e ...
- 各种反演细节梳理&模板
炫酷反演魔术课件byVFK stO FDF Orz(证明全有%%%) 莫比乌斯反演 \(F(n)=\sum\limits_{d|n}f(d)\Rightarrow f(n)=\sum\limits_{ ...
- Android 可展开列表组件 ExpandableListView
ExpandableListView 是ListView的子类,它把应用中的列表项分为几组,每组里可包含多个列表项. 所显示的列表项应该由ExpandableListAdapter 接口提供,实现Ex ...
- IP地址等价类测试用例
下面是一个比较完善的设计方案,这个方案中,首先把IP地址分成有效可用的IP地址和有效但不可用的IP地址两个等价类:其中有效可用的IP地址中包括IP地址的A,B,C三类地址,有效但不可用的IP地址包括D ...
- This license xxx has been cancelled 解决
上节回顾:JetBrains全家桶破解思路 hosts屏蔽一下即可,Linux是:/etc/hosts 0.0.0.0 account.jetbrains.com 重新输入Code即可,最后补一个地址 ...
- AITP
AITP AITP比较简单,适合刚毕业,即将开始IT生涯的学生.接受CIPS认证课程的毕业生可以自动获得AITP证书,并获得一年的免费的CIPS会员资格. 接受非CIPS认证课程的毕业生需要申请,另外 ...
- [CTSC2010]性能优化
[CTSC2010]性能优化 循环卷积快速幂 两个注意点:n+1不是2^k*P+1形式,任意模数又太慢?n=2^k1*3^k2*5^k3*7^k4 多路分治!深刻理解FFT运算本质:分治,推式子得到从 ...
- luogu2643 聪聪可可
题目链接 题意 其实转化之后的题意就是求出树上有多少条路径长度是3的倍数.求答案的时候只要将这个数字除以总路径数量就行了. 思路 考虑点分治.对于当前子树,分别求出出树中每个点到根的路径长度对\(3\ ...
- 软件在 win7 上运行时显示乱码
一个用户反应后,我当时就蒙圈了,因为之前从未遇到过: 百度一下后,发现用户的这种情况比较特殊,从表面上看,[控制面板]和[注册表]相关项设置都正常,为什么还显示乱码呢? 到最后一步如果已经是(简体,中 ...
- bzoj1791[IOI2008]Island岛屿(基环树+DP)
题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=1791 题目大意:给你一棵n条边的基环树森林,要你求出所有基环树/树的直径之和.n< ...