隧道转发的原理

1,104 阅读2分钟

网络爬虫都知道使用HTTP代理去进行业务采集,效果和质量都会上升。使用过HTTP代理的爬虫用户都知道,代理分为两种。一种是传统的API优质代理和隧道转发的爬虫代理加强版。

API代理:

传统API提取式代理,通过URL定时获取代理IP信息,需验证IP的可用性、更换代理设置,同时需要设计多线程异步IO,实现代理IP并发处理,不仅繁琐,而且影响效率。

隧道转发代理:

“亿牛云爬虫代理IP”通过固定云代理服务地址,建立专线网络链接,代理平台自动实现毫秒级代理IP切换,保证了网络稳定性和速度,避免爬虫客户在代理IP策略优化上投入精力。

隧道转发代理的工作流程:

设置一个隧道代理服务器,发出请求随机分配一个代理IP。代理服务器会将这些请求转发给目标网站服务器,然后返回数据信息给隧道代理服务器然后转发给客户端即可

// 要访问的目标页面
string targetUrl = "http://httpbin.org/ip";

// 代理服务器(产品官网 www.16yun.cn)
string proxyHost = "http://t.16yun.cn";
string proxyPort = "31111";

// 代理验证信息
string proxyUser = "username";
string proxyPass = "password";

// 设置代理服务器
WebProxy proxy = new WebProxy(string.Format("{0}:{1}", proxyHost, proxyPort), true);

ServicePointManager.Expect100Continue = false;

var request = WebRequest.Create(targetUrl) as HttpWebRequest;

request.AllowAutoRedirect = true;
request.KeepAlive = true;
request.Method    = "GET";
request.Proxy     = proxy;

//request.Proxy.Credentials = CredentialCache.DefaultCredentials;

request.Proxy.Credentials = new System.Net.NetworkCredential(proxyUser, proxyPass);

// 设置Proxy Tunnel
// Random ran=new Random();
// int tunnel =ran.Next(1,10000);
// request.Headers.Add("Proxy-Tunnel", String.valueOf(tunnel));

//request.Timeout = 20000;
//request.ServicePoint.ConnectionLimit = 512;
//request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36";
//request.Headers.Add("Cache-Control", "max-age=0");
//request.Headers.Add("DNT", "1");

//String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(proxyUser + ":" + proxyPass));
//request.Headers.Add("Proxy-Authorization", "Basic " + encoded);

using (var response = request.GetResponse() as HttpWebResponse)
using (var sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
    string htmlStr = sr.ReadToEnd();
}

以上可看出API代理使用比较麻烦,而隧道转发代理使用方便简单,速度快。