.net之訪問Internet(上)

.net提供了使用各種網絡協議訪問網絡和Internet的類庫

1. WebClient類

    如果只是想從某個網站上讀取文件,使用WebClient類就足夠了,它通過一兩個簡單的命令就可以執行一些基本操作。使用起來非常簡單,創建一個WinForm工程,添加ListBox控件,將百度頁面的內容讀取出來。WebClient類還有UploadFile和UploadData方法可以上傳文件

    代碼示例: 

        public Form1()
        {
            InitializeComponent();

            System.Net.WebClient Client = new WebClient();//創建client
            Stream strm = Client.OpenRead("http://www.baidu.com");//創建讀取流
            StreamReader sr = new StreamReader(strm);
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                listBox1.Items.Add(line);
            }

            strm.Close();//關閉流

        }

2. WebRequest類和WebResponse類

    WebClient類使用起來很簡單,但是不能使用它提供身份驗證證書,在使用它上傳文件時,好多網站不接收沒有身份驗證的上傳文件。而且WebClient可以使用任意協議接收和發送請求,這樣它就不能處理類似於HTTP的cookie信息。如果想使用這些特性,就要使用WebRequest類和WebResponse類。

    獲取HTTP標題信息示例: 

    WebRequest wrq = WebRequest.Create("http://www.baidu.com");
    HttpWebRequest hwrq = (HttpWebRequest)wrq;

    listBox1.Items.Add("Request Timeout (ms) = " + wrq.Timeout);
    listBox1.Items.Add("Request Keep Alive = " + hwrq.KeepAlive);
    listBox1.Items.Add("Request AllowAutoRedirect = " + hwrq.AllowAutoRedirect);
    listBox1.Items.Add("\r\n");

    WebResponse wrs = wrq.GetResponse();
    WebHeaderCollection whc = wrs.Headers;
    for(int i = 0; i< whc.Count; i++)
    {
        listBox1.Items.Add("Header " + whc.GetKey(i) + " : " + whc[i]);
    }

    使用身份驗證:在GetResponse之前給wrq的Credentials附上值,如下,

    NetworkCredential myCred = new NetworkCredential("myusername", "mypassword");
    wrq.Credentials = myCred;

    異步頁面請求:   

    public Form1()
    {
        InitializeComponent();

        WebRequest wrq = WebRequest.Create("http://www.baidu.com");
        wrq.BeginGetResponse(new AsyncCallback(OnResponse), wrq);//異步啓動請求,OnResponse方法實際響應請求

    }
    protected void OnResponse(IAsyncResult ar)
    {
        WebRequest wrq = (WebRequest)ar.AsyncState;
        WebResponse wrs = wrq.EndGetResponse(ar);
        //to do read
    }

3. 把輸出結果顯示成爲HTML頁面,神奇WebBrowser類

    WebBrowser類可以讓用戶在窗體中導航網頁,裏面有衆多IE所具有的屬性可以用,還可以通過 Document 屬性操作網頁的內容

    WebBrowser.Navigate(“訪問地址”),就可以加載到需要訪問的網頁,它還支持前進後退等各種操作


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章