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

    技术2022-05-11  112

    开始写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, 0256);             } OK,这样就完成了代码设置我们的代理,直接通过程序来访问IE内容了~~ 

    最新回复(0)