MSDN:WebClient提供向 URI 標識的資源發送資料和從 URI 標識的資源接收資料的公用方法.
Demo(一):簡單的請求請求一個頁面內容
View Code
using System;using System.IO;using System.Net;namespace ConsoleApplication2{ class Program { static void Main(string[] args) { String url = "http://www.baidu.com"; //先設定代理(在使用代理進行上網的時候用,如果沒有使用代理則無需設定) WebProxy proxy = new WebProxy("192.168.19.9", 80); //建立 Proxy 伺服器設定對象 的執行個體 proxy.BypassProxyOnLocal = false; //Proxy 伺服器需要驗證 proxy.Credentials = new NetworkCredential("jiaquanzhen", "abcd_123", "yellowpage"); //使用者名稱密碼 GlobalProxySelection.Select = proxy; //開始請求 WebClient client = new WebClient(); //佈建要求的資源種類 client.Headers.Add("Accept", @"image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); client.Headers.Add("Accept-Language", "zh-cn,zh;q=0.5"); //擷取網上資源的stream System.IO.Stream stream = client.OpenRead(url); //解碼擷取內容 System.IO.StreamReader reader = new System.IO.StreamReader(stream, System.Text.Encoding.UTF8); String str = reader.ReadToEnd(); Console.WriteLine(str); } }}
Demo(二):非同步請求擷取資料
View Code
using System;using System.Web;using System.Web.UI;using System.IO;using System.Net;using System.Text;namespace WebApp{ public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.btnBegin.Click += new EventHandler(btnBegin_Click); } void btnBegin_Click(object sender, EventArgs e) { //請求的url Uri uri = new Uri("http://www.baidu.com"); //初始化webclient,並設定頭屬性 WebClient client = new WebClient(); client.Headers.Add("Accept", @"image/gif,image/x-xbitmap,image/jpeg,application/x-shockwave-flash, appllication/vnd.ms-excel,application/vnd.ms-powerpoint,aplication/msword,*/*"); client.Headers.Add("Accept-Language", "zh-cn,zh;q=0.5"); //進行非同步讀取 client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted); client.OpenReadAsync(uri); } //回呼函數 void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { Stream stream = e.Result; StreamReader reader = new StreamReader(stream, Encoding.Default); String str = reader.ReadToEnd(); Response.Write(str); } }}