Three ways to get web page content in C#

Search the web and find that C# usually has three ways to get web page content, using WebClient, WebBrowser or HttpWebRequest/HttpWebResponse. . .

Method 1: Use WebClient (quoted from: http://fbljava.blog.163.com/blog/static/265211742008712105145244/ )

static void Main(string[] args)

{

    try {

        WebClient MyWebClient = new WebClient();

        
        MyWebClient.Credentials = CredentialCache.DefaultCredentials;//Gets or sets the network credentials used to authenticate requests to Internet resources

        Byte[] pageData = MyWebClient.DownloadData(" http://www.163.com");  //Download data from the specified website

        string pageHtml = Encoding.Default.GetString(pageData); //If GB2312 is used to get the website page, use this sentence            

        //string pageHtml = Encoding.UTF8.GetString(pageData); //If the website page is obtained in UTF-8, use this sentence

        Console.WriteLine(pageHtml);//Enter the acquired content in the console

        using (StreamWriter sw = new StreamWriter("c:\\test\\ouput.html"))//Write the acquired content to text

        {

            sw.Write(pageHtml);

        }

        Console.ReadLine(); //Let the console pause, otherwise it will flash over             

    }

    catch(WebException webEx) {

        Console.WriteLine(webEx.Message.ToString());

    }

}

Method 2: Use WebBrowser (quoted from: http://topic.csdn.net/u/20091225/14/4ea221cd-4c1e-4931-a6db-1fd4ee7398ef.html )

WebBrowser web = new WebBrowser(); 
web.Navigate("http://www.xjflcp.com/ssc/"); 
web.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted); 
void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
        { 
            WebBrowser web = (WebBrowser)sender; 
            HtmlElementCollection ElementCollection = web.Document.GetElementsByTagName("Table"); 
            foreach (HtmlElement item in ElementCollection) 
            { 
                 File.AppendAllText("Kaijiang_xj.txt", item.InnerText); 
            } 
        }

方法三:使用HttpWebRequest/HttpWebResponse (引用自:http://hi.baidu.com/onlyafar/blog/item/7ac4c6bf92d4810019d81f98.html

HttpWebRequest httpReq; 
HttpWebResponse httpResp; 

string strBuff = ""; 
char[] cbuffer = new char[256]; 
int byteRead = 0; 

string filename = @"c:\log.txt"; 
///定义写入流操作 
public void WriteStream() 

Uri httpURL = new Uri(txtURL.Text);

///HttpWebRequest类继承于WebRequest,并没有自己的构造函数,需通过WebRequest的Creat方法 建立,并进行强制的类型转换 
      httpReq = (HttpWebRequest)WebRequest.Create(httpURL); 
///通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换

   httpResp = (HttpWebResponse) httpReq.GetResponse(); 
///GetResponseStream()方法获取HTTP响应的数据流,并尝试取得URL中所指定的网页内容

     ///若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错 误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理 
Stream respStream = httpResp.GetResponseStream();

///返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以

StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8) 
StreamReader respStreamReader = new StreamReader(respStream,Encoding.UTF8);

byteRead = respStreamReader.Read(cbuffer,0,256); 

while (byteRead != 0) 

string strResp = new string(cbuffer,0,byteRead); 
                  strBuff = strBuff + strResp; 
                  byteRead = respStreamReader.Read(cbuffer,0,256); 


respStream.Close(); 
txtHTML.Text = strBuff; 
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325559139&siteId=291194637