網頁擷取(1) 利用WebClient

  • 3440
  • 0
  • 2011-10-20

摘要:網頁擷取(1) 利用WebClient

01 using System.Net;
02 using System.IO;
03 using System.Text;

04
05 public void _WebClient(string url)
06         {
07             WebClient wc = new WebClient();
08
09             // 依照預設值,WebClient 執行個體並不會傳送選擇性的 HTTP 標頭。
10             // 如果您的要求需要有選擇性的標頭,您就必須將標頭加入至 Headers  集合中。
11             // 例如,若要在回應中保留查詢,您就必須加入使用者代理程式 (User-Agent) 的標頭。
12             // 同時,如果遺失使用者代理程式標頭,則伺服器可能傳回 500 (內部伺服器錯誤)。
13             wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
14
15             // 表示支援壓縮,也就是說,你可以丟壓縮過的資料過來
16             // wc.Headers.Add("Accept-Encoding","gzip, deflate");
17
18             Stream data = wc.OpenRead(url);
19
20             //要知道正確的編碼,再去讀取! StreamReader 預設值為 UTF-8 編碼方式
21
22             //StreamReader reader = new StreamReader(data, Encoding.GetEncoding("gb2312"));//簡體
23             
24             StreamReader reader = new StreamReader(data);            
25             string s = reader.ReadToEnd();
26
27               data.Close();
28             reader.Close();
29
30         }

31

==============================================================

參考:

http://blog.roodo.com/thinkingmore/archives/2782355.html

http://msdn.microsoft.com/zh-tw/library/system.net.webclient%28VS.80%29.aspx