開始寫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內容了~~