網路編程之WebClient,WebRequest和WebResponse類

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   io   資料   

一.基本的WebClient類

1.首先使用OpenRead()方法返回一個stream流對象

2.把Stream流對象轉換為StreamReader對象

3.使用ReadLine()方法從資料流中以文本的方式擷取資料

            WebClient web = new WebClient();            Stream stream = web.OpenRead("http://www.reuters.com");            StreamReader sr = new StreamReader(stream);            while (sr.ReadLine() != null)            {                string line;                line = sr.ReadLine();                listBox1.Items.Add(line);            }            stream.Close();

二.WebRequest和WebResponse類

.WebRequest代表要給某個特定URI發送資訊的請求,uri作為參數傳遞給Create()方法,WebResponse類代表從伺服器檢索的資料

1.建立新的線程來請求頁面

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.Net;using System.IO;using System.Threading;namespace WindowsFormsApplication1{    public delegate void mydelegate(WebHeaderCollection s); //聲明委託    public partial class Form1 : Form    {        Thread x;        public Form1()        {            InitializeComponent();            WebRequest wrq = WebRequest.Create("http://www.reuters.com");            //定義一個線程            x = new Thread(doresponse);            //啟動線程            x.Start(wrq);        }        private void doresponse(object ar)        {            WebRequest wrq = (WebRequest)ar;            WebResponse wrp = wrq.GetResponse();            WebHeaderCollection whc = wrp.Headers;//wrp.Headers:擷取與請求相關聯的標題值的集合            mydelegate my = new mydelegate(settext);//聲明委託執行的方法為settext()            this.Invoke(my, new object[] { whc });//在擁用此控制項的基礎表單控制代碼的線程上執行指定的委託,此方法第二參數用於傳入方法,代替形參whc        }                private void settext(WebHeaderCollection whc)        {            for (int i = 0; i < whc.Count; i++)            {                listBox1.Items.Add(string.Format("name {0}:{1}", whc.GetKey(i), whc[i]));//GetKey(i)代表擷取指定索引的標題名稱,whc[i]和whc.Get(i)代表擷取特定標題名稱的值                listBox1.Items.Add(string.Format("name name {0}:{1}", whc.GetKey(i), whc.Get(i)));            }            x.Abort();//關閉這個線程        }    }}

2.使用非同步方法呼叫進行頁面請求

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.Net;using System.IO;using System.Threading;namespace WindowsFormsApplication1{    public delegate void mydelegate(WebHeaderCollection s);     public partial class Form1 : Form    {        Thread x;        public Form1()        {            InitializeComponent();            WebRequest wrq = WebRequest.Create("http://www.reuters.com");            //把身分識別驗證認證附在請求中            NetworkCredential myCredentials = new NetworkCredential("lzw", "123");            HttpWebRequest hwrq = (HttpWebRequest)wrq;//可以在任何需要WebRequest類的地方使用衍生類別HttpWebRequest            hwrq.Credentials = myCredentials;//擷取身分識別驗證資訊
//HttpWebRequest類特有的屬性: listBox1.Items.Add("等待異常拋出的時間:" + hwrq.Timeout);//hwrq.Timeout預設值100000毫秒 listBox1.Items.Add("是否與 Internet 資源建立持久性串連:" + hwrq.KeepAlive);//預設為true listBox1.Items.Add("是否自動跟隨web重新導向響應:" + hwrq.AllowAutoRedirect);//預設為true //非同步頁面請求 IAsyncResult ar = hwrq.BeginGetResponse(null, null); hwrq = (HttpWebRequest)ar.AsyncState; WebResponse wrp = wrq.EndGetResponse(ar); WebHeaderCollection whc = wrp.Headers;//wrp.Headers:擷取與請求相關聯的標題值的集合 for (int i = 0; i < whc.Count; i++) { listBox1.Items.Add(string.Format("name {0}:{1}", whc.GetKey(i), whc[i]));//GetKey(i)代表擷取指定索引的標題名稱,whc[i]和whc.Get(i)代表擷取特定標題名稱的值 listBox1.Items.Add(string.Format("name name {0}:{1}", whc.GetKey(i), whc.Get(i))); } } }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.