c# HttpWebRequest通過Proxy 伺服器抓取網頁內容應用介紹

來源:互聯網
上載者:User

內網使用者或代理上網的使用者使用 複製代碼 代碼如下:using System.IO;
using System.Net;
public string get_html()
{
string urlStr = "http://www.domain.com"; //設定要獲取的地址
HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(urlStr); //建立HttpWebRequest對象
hwr.Timeout = 60000; //定義服務器超時時間
WebProxy proxy = new WebProxy(); //定義一個網關對象
proxy.Address = new Uri("http://proxy.domain.com:3128"); //網關服務器:連接埠
proxy.Credentials = new NetworkCredential("f3210316", "6978233"); //用戶名,密碼
hwr.UseDefaultCredentials = true; //啟用網關認証
hwr.Proxy = proxy; //設置網關
try
{
HttpWebResponse hwrs = (HttpWebResponse)hwr.GetResponse(); //取得回應
}
catch
{
MessageBox.Show("無法串連代理!");
return;
}
//判斷HTTP響應狀態
if(hwrs.StatusCode != HttpStatusCode.OK)
{
MessageBox.Show("訪問失敗!");
hwrs.Close();
return;
}
else
{
Stream s = hwrs.GetResponseStream(); //得到回應的流對象
StreamReader sr = new StreamReader(s, Encoding.UTF8); //以UTF-8編碼讀取流
StringBuilder content = new StringBuilder(); //
while (sr.Peek() != -1) //每次讀取一行,直到
{ //下一個字節沒有內容
content.Append(sr.ReadLine()+""r"n"); //返回為止
} //
//return content.ToString() ;
}
//輸出所有的Header(當然包括伺服器輸出的Cookie)
//for(int ii=0;ii<hwrs.Headers.Count;ii++)
//{
//MessageBox.Show(hwrs.Headers.GetKey(ii)+":"+res.Headers[ii]);
//}
}

大家知道,用HttpWebRequest可以通過Http對網頁進行抓取,但是如果是內網,而且是通過代理上網的使用者,如果直接進行操作是行不通的。
那有沒有什麼辦法呢?
當然有,呵呵,見以下代碼: 複製代碼 代碼如下:string urlStr = "http://www.domain.com"; //設定要獲取的地址
HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(urlStr); //建立HttpWebRequest對象
hwr.Timeout = 60000; //定義服務器超時時間
WebProxy proxy = new WebProxy(); //定義一個網關對象
proxy.Address = new Uri("http://proxy.domain.com:3128"); //網關服務器:連接埠
proxy.Credentials = new NetworkCredential("f3210316", "6978233"); //用戶名,密碼
hwr.UseDefaultCredentials = true; //啟用網關認証
hwr.Proxy = proxy; //設置網關
HttpWebResponse hwrs = (HttpWebResponse)hwr.GetResponse(); //取得回應
Stream s = hwrs.GetResponseStream(); //得到回應的流對象
StreamReader sr = new StreamReader(s, Encoding.UTF8); //以UTF-8編碼讀取流
StringBuilder content = new StringBuilder(); //
while (sr.Peek() != -1) //每次讀取一行,直到
{ //下一個字節沒有內容
content.Append(sr.ReadLine()+""r"n"); //返回為止
} //
return content.ToString() ; //返回得到的字串

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.