繁体中文
设为首页
加入收藏
当前位置:.Net技术首页 >> Asp.Net开发 >> 在C#代码中设置Http访问代理服务器

在C#代码中设置Http访问代理服务器

2007-09-15 08:00:00  作者:  来源:互联网  浏览次数:0  文字大小:【】【】【
简介:开始写Blog读取工具时一直是直接访问,访问方式也比较简单: WebRequest _HWR = WebRequest.CreateDefault(new System.Uri(URL)); WebResponse _HRS = _HWR.GetResponse() ; Stream ReceiveStream = _HRS.GetR...

开始写Blog读取工具时一直是直接访问,访问方式也比较简单:

WebRequest _HWR = WebRequest.CreateDefault(new System.Uri(URL));

WebResponse _HRS = _HWR.GetResponse() ;

Stream ReceiveStream = _HRS.GetResponseStream();

但是最近打开工程一看,代码运行不正常,调试了一下,原来客户端代理被ITS封掉了,只得去查找设置代理访问的方法,原来代码很简单,只需要加入下面代码即可。

WebProxy _WP = new WebProxy(ProxyName,ProxyPort);

_WP.BypassProxyOnLocal = true;

ICredentials credentials = new NetworkCredential(UserName,UserKey,DomainName);

_WP.Credentials = credentials;

WebRequest _HWR = WebRequest.CreateDefault(new System.Uri(URL));

_HWR.Proxy = _WP;

WebResponse _HRS = _HWR.GetResponse() ;

当然,MSDN上对于_HWR.Proxy = _WP;还有另外一个使用方式

GlobalProxySelection.Select = _WP;其实也就是设置全局的代理服务,不需要再一一设置,抓取页面数据就比较简单了。

Encoding encode = System.Text.Encoding.Default;

StreamReader sr = new StreamReader( ReceiveStream, encode );

string HTMLContent = "";

Char[] read = new Char[256];

int count = sr.Read( read, 0, 256 );

while (count > 0)

{

String str = new String(read, 0, count);

HTMLContent += str;

count = sr.Read(read, 0, 256);

}

OK,这样就完成了代码设置我们的代理,直接通过程序来访问IE内容了~~

----------------

全部代码:

private string LoadHTML(string ProxyName,int ProxyPort,string UserName,string UserKey,

string DomainName,string URL)

{

//读取HTML内容

WebProxy _WP = new WebProxy(ProxyName,ProxyPort);

_WP.BypassProxyOnLocal = true;

ICredentials credentials = new NetworkCredential(UserName,UserKey,DomainName);

_WP.Credentials = credentials;

//GlobalProxySelection.Select = _WP;

WebRequest _HWR = WebRequest.CreateDefault(new System.Uri(URL));

_HWR.Proxy = _WP;

WebResponse _HRS = _HWR.GetResponse() ;

Stream ReceiveStream = _HRS.GetResponseStream();

Encoding encode = System.Text.Encoding.Default;

StreamReader sr = new StreamReader( ReceiveStream, encode );

string HTMLContent = "";

Char[] read = new Char[256];

int count = sr.Read( read, 0, 256 );

while (count > 0)

{

String str = new String(read, 0, count);

HTMLContent += str;

count = sr.Read(read, 0, 256);

}

return HTMLContent;

}

责任编辑:admin
相关文章