程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> WebClient類

WebClient類

編輯:C#基礎知識

WebClient類提供向 URI 標識的資源發送數據和從 URI 標識的資源接收數據的公共方法。 其實就相當於創建一個請求客戶端。可以獲取網頁和各種各樣的信息,包括交互。

通過MSDN來看看WebClient類提供的功能。

一、屬性

1、BaseAddress 獲取或設置 WebClient 發出請求的基 URI。
2、CachePolicy 對於此 WebClient 實例使用 WebRequest 對象獲得的任何資源,獲取或設置應用程序的緩存策略。
3、CanRaiseEvents 獲取一個指示組件是否可以引發事件的值。 (繼承自 Component。)
4、Container 獲取 IContainer,它包含 Component。 (繼承自 Component。)
5、Credentials 獲取或設置發送到主機並用於對請求進行身份驗證的網絡憑據。
6、DesignMode 獲取一個值,用以指示 Component 當前是否處於設計模式。 (繼承自 Component。)
7、Encoding 獲取和設置用於上載和下載字符串的 Encoding。
8、Events 獲取附加到此 Component 的事件處理程序的列表。 (繼承自 Component。)
9、Headers 獲取或設置與請求關聯的標頭名稱/值對集合。
10、IsBusy 了解是否存在進行中的 Web 請求。
11、Proxy 獲取或設置此 WebClient 對象使用的代理。
12、QueryString 獲取或設置與請求關聯的查詢名稱/值對集合。
13、ResponseHeaders 獲取與響應關聯的標頭名稱/值對集合。
14、Site 獲取或設置 Component 的 ISite。 (繼承自 Component。)
15、UseDefaultCredentials 獲取或設置 Boolean 值,該值控制 DefaultCredentials 是否隨請求一起發送。

二、方法

1、CancelAsync 取消一個掛起的異步操作。
2、CreateObjRef 創建一個對象,該對象包含生成用於與遠程對象進行通信的代理所需的全部相關信息。 (繼承自 MarshalByRefObject。)
3、Dispose 已重載。 
4、DownloadData 已重載。 以 Byte 數組形式通過指定的 URI 下載。
5、DownloadDataAsync 已重載。 以 Byte 數組形式下載指定的資源。這些方法不會阻止調用線程。
6、DownloadFile 已重載。 將具有指定 URI 的資源下載到本地文件。
7、DownloadFileAsync 已重載。 將指定的資源下載到本地文件。這些方法不會阻止調用線程。
8、DownloadString 已重載。 以 String 形式下載請求的資源。可以以包含 URI 的 String 或 Uri 的形式指定要下載的資源。
9、DownloadStringAsync 已重載。 下載以 String 或 Uri 形式指定的資源。這些方法不會阻止調用線程。
10、Equals 確定指定的 Object 是否等於當前的 Object。 (繼承自 Object。)
11、Finalize 在通過垃圾回收將 Component 回收之前,釋放非托管資源並執行其他清理操作。 (繼承自 Component。)
12、GetHashCode 用作特定類型的哈希函數。 (繼承自 Object。)
13、GetLifetimeService 檢索控制此實例的生存期策略的當前生存期服務對象。 (繼承自 MarshalByRefObject。)
14、GetService 返回一個對象,該對象表示由 Component 或它的 Container 提供的服務。 (繼承自 Component。)
15、GetType 獲取當前實例的 Type。 (繼承自 Object。)
16、GetWebRequest 為指定資源返回一個 WebRequest 對象。
17、GetWebResponse 已重載。 返回對指定 WebRequest 的 WebResponse。
18、InitializeLifetimeService 獲取控制此實例的生存期策略的生存期服務對象。 (繼承自 MarshalByRefObject。)
19、MemberwiseClone 已重載。
20、OnDownloadDataCompleted 引發 DownloadDataCompleted 事件。
21、OnDownloadFileCompleted 引發 DownloadFileCompleted 事件。
22、OnDownloadProgressChanged 引發 DownloadProgressChanged 事件。
23、OnDownloadStringCompleted 引發 DownloadStringCompleted 事件。
24、OnOpenReadCompleted 引發 OpenReadCompleted 事件。
25、OnOpenWriteCompleted 引發 OpenWriteCompleted 事件。
26、OnUploadDataCompleted 引發 UploadDataCompleted 事件。
27、OnUploadFileCompleted 引發 UploadFileCompleted 事件。
28、OnUploadProgressChanged 引發 UploadProgressChanged 事件。
29、OnUploadStringCompleted 引發 UploadStringCompleted 事件。
30、OnUploadValuesCompleted 引發 UploadValuesCompleted 事件。
31、OpenRead 已重載。 為從具有指定 URI 的資源下載的數據打開一個可讀的流。
32、OpenReadAsync 已重載。 打開包含指定資源的可讀流。這些方法不會阻止調用線程。
33、OpenWrite 已重載。 打開一個流以將數據寫入具有指定 URI 的資源。
34、OpenWriteAsync 已重載。 打開一個流以將數據寫入指定的資源。這些方法不會阻止調用線程。
35、ToString 返回包含 Component 的名稱的 String(如果有)。不應重寫此方法。 (繼承自 Component。)
36、UploadData 已重載。 將數據緩沖區上載到具有指定 URI 的資源。
37、UploadDataAsync 已重載。 將數據緩沖區上載到由 URI 標識的資源。此方法不會阻止調用線程。
38、UploadFile 已重載。 將本地文件上載到具有指定 URI 的資源。
39、UploadFileAsync 已重載。 將指定的本地文件上載到指定的資源。這些方法不會阻止調用線程。
40、UploadString 已重載。 將指定的字符串上載到指定的資源。
41、UploadStringAsync 已重載。 將指定的字符串上載到指定的資源。這些方法不會阻止調用線程。
42、UploadValues 已重載。 將名稱/值集合上載到具有指定 URI 的資源。
43、UploadValuesAsync 已重載。 將指定的名稱/值集合上載到指定的 URI 所標識的資源。這些方法不會阻止調用線程。

三、事件

1、Disposed 當通過調用 Dispose 方法釋放組件時發生。 (繼承自 Component。)
2、DownloadDataCompleted 在異步數據下載操作完成時發生。
3、DownloadFileCompleted 在異步文件下載操作完成時發生。
4、DownloadProgressChanged 在異步下載操作成功轉換部分或全部數據後發生。
5、DownloadStringCompleted 在異步資源下載操作完成時發生。
6、OpenReadCompleted 在以下異步操作完成時發生,該操作打開包含某個資源的流。
7、OpenWriteCompleted 在打開流以將數據寫入資源的異步操作完成時發生。
8、UploadDataCompleted 在異步數據上載操作完成時發生。
9、UploadFileCompleted 在異步文件上載操作完成時發生。
10、UploadProgressChanged 在異步上載操作成功轉換部分或全部數據後發生。
11、UploadStringCompleted 在異步字符串上載操作完成時發生。
12、UploadValuesCompleted 在名稱/值集合的異步上載完成時發生。

 該類在小偷程序以及采集器時經常用到,以下給個比較簡單的例子。

        static void Main(string[] args)
        {
            WebClient wc = new WebClient();
            wc.BaseAddress = "http://www.juedui100.com/";   //設置根目錄
            wc.Encoding = Encoding.UTF8;                    //設置按照何種編碼訪問,如果不加此行,獲取到的字符串中文將是亂碼
            string str = wc.DownloadString("/");
            Console.WriteLine(str);


            //----------------------以下為OpenRead()以流的方式讀取----------------------
            wc.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, */*");
            wc.Headers.Add("Accept-Language", "zh-cn");
            wc.Headers.Add("UA-CPU", "x86");
            //wc.Headers.Add("Accept-Encoding","gzip, deflate");    //因為我們的程序無法進行gzip解碼所以如果這樣請求獲得的資源可能無法解碼。當然我們可以給程序加入gzip處理的模塊 那是題外話了。
            wc.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
            //Headers   用於添加添加請求的頭信息
            System.IO.Stream objStream = wc.OpenRead("user/6974068.html");      //獲取訪問流
            System.IO.StreamReader _read = new System.IO.StreamReader(objStream, System.Text.Encoding.UTF8);    //新建一個讀取流,用指定的編碼讀取,此處是utf-8
            Console.Write(_read.ReadToEnd());   //輸出讀取到的字符串

            //------------------------DownloadFile下載文件-------------------------------
            wc.DownloadFile("http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.gif", @"D:\123.gif");     //將遠程文件保存到本地
            //------------------------DownloadFile下載到字節數組-------------------------------
            byte[] bytes = wc.DownloadData("http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.gif");
            FileStream fs = new FileStream(@"E:\123.gif", FileMode.Create);
            fs.Write(bytes, 0, bytes.Length);
            fs.Flush();

            WebHeaderCollection whc = wc.ResponseHeaders;   //獲取響應頭信息
            foreach (string s in whc)
            {
                Console.WriteLine(s + ":" + whc.Get(s));
            }

            Console.WriteLine(wc.QueryString.Count);    //輸出0

            Console.ReadKey();
        }

   附上一個異步下載頁面的例子:

public class Program
    {
        static void Main(string[] args)
        {
            WebClient wc = new WebClient();
            wc.Encoding = Encoding.UTF8;                    //設置按照何種編碼訪問,如果不加此行,獲取到的字符串中文將是亂碼
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownComplete);
            wc.DownloadStringAsync(new Uri("http://www.juedui100.com/"));
            Console.WriteLine("下載!");

            Console.ReadKey();
        }

        public static void DownComplete(object sender, DownloadStringCompletedEventArgs e)
        {
            Console.WriteLine(sender.ToString());   //輸出 System.Net.WebClient   觸發事件的對象
            Console.WriteLine(e.Result);    //輸出頁面源代碼
        }
    }

   匿名委托:

    public class Program
    {
        static void Main(string[] args)
        {
            WebClient wc = new WebClient();
            wc.Encoding = Encoding.UTF8;                    //設置按照何種編碼訪問,如果不加此行,獲取到的字符串中文將是亂碼
            wc.DownloadStringCompleted += (sender, e) =>
                {
                    Console.WriteLine(sender.ToString());   //輸出 System.Net.WebClient   觸發事件的對象
                    Console.WriteLine(e.Result);    //輸出頁面源代碼
                };
            wc.DownloadStringAsync(new Uri("http://www.baidu.com/"));
            Console.WriteLine("下載完成");

            Console.ReadKey();
        }
    }

   WebClient下載文件DEMO:

public class Program
    {
        static void Main(string[] args)
        {
            WebClient wc = new WebClient();
            //直接下載
            wc.DownloadFile("http://24.duote.com.cn/kugou.zip", @"D:\ku.zip");
            Console.WriteLine("下載完成了嗎?");   //下載完成後輸出 下載完成了嗎?

            //異步下載
            wc.DownloadFileAsync(new Uri("http://24.duote.com.cn/kugou.zip"), @"D:\kugou.zip");
            wc.DownloadFileCompleted += DownCompletedEventHandler;
            Console.WriteLine("現在完成了還是沒完成呢?");

            //匿名委托
            wc.DownloadFileAsync(new Uri("http://24.duote.com.cn/kugou.zip"), @"D:\kugou.zip");
            wc.DownloadFileCompleted += (sender, e) =>
            {
                Console.WriteLine("下載完成!");
                Console.WriteLine(e.UserState);
                Console.WriteLine(e.Cancelled);
            };
            Console.WriteLine("現在完成了還是沒完成呢?");
            Console.ReadKey();
        }

        public static void DownCompletedEventHandler(object sender, AsyncCompletedEventArgs e)
        {
            Console.WriteLine("下載完成!");
            Console.WriteLine(e.UserState);
            Console.WriteLine(e.Cancelled);
        }
    }

  第二,第三個方法顯示如下:

  

   將數據下載到字節數組:

        static void Main(string[] args)
        {
            WebClient wc = new WebClient();
            //直接下載
            wc.DownloadFile("http://24.duote.com.cn/kugou.zip", @"D:\ku.zip");
            Console.WriteLine("下載完成了嗎?");   //下載完成後輸出 下載完成了嗎?

            //將數據下載到字節數組
            byte[] byteArr = wc.DownloadData("http://24.duote.com.cn/kugou.zip");
            FileStream fs = new FileStream(@"D:\kugo.zip",FileMode.OpenOrCreate,FileAccess.ReadWrite);
            fs.Write(byteArr,0,byteArr.Length);

            //至於異步與下載雷同
            
            Console.WriteLine("現在完成了還是沒完成呢?");
            Console.ReadKey();
        }

  WebClient的OpenRead()方法,下載成一個Stream

public class Program
    {
        
        static void Main(string[] args)
        {
            WebClient wc = new WebClient();

       //直接下載成Stream //Stream stream = wc.OpenRead("http://www.baidu.com/"); //StreamReader sr = new StreamReader(stream); //Console.WriteLine(sr.ReadToEnd()); wc.OpenReadAsync(new Uri("http://www.baidu.com")); wc.OpenReadCompleted += (sender, e) => { Console.WriteLine("下載完成!"); Console.WriteLine(e.UserState); StreamReader sr = new StreamReader(e.Result); Console.WriteLine(sr.ReadToEnd()); }; Console.ReadKey(); } public static void ReadCompleted(object sender, OpenReadCompletedEventArgs e) { Console.WriteLine("下載完成!"); Console.WriteLine(e.UserState); StreamReader sr = new StreamReader(e.Result); Console.WriteLine(sr.ReadToEnd()); } }

WebClient不能處理特定於任何協議的任何特性,例如Cookie等。如果需要使用這些特性,需要使用.net中的HttpWebRequest類。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved