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

C#獲取網頁內容

編輯:C#入門知識

susing System.Net;
\using System.IO;
\using System.Text;
\
       
\            //方法一:
\            // Create a request for the URL.  

WebRequest request = WebRequest.Create("http://www.hao123.com/");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // Display the status.
            Response.Write(response.StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream,Encoding.Default);// 注:漢字需要轉為UTF8格式
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Response.Write(responseFromServer);
            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();
        

            //方法二:
            WebClient client = new WebClient();

            // Add a user agent header in case the
            // requested URI contains a query.

            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

            Stream data = client.OpenRead("http://www.hao123.com/");
            StreamReader reader = new StreamReader(data,Encoding.Default); // 注:漢字需要轉為UTF8格式
            string s = reader.ReadToEnd();
            Response.Write(s);
            data.Close();
            reader.Close();
           
            //方法三:
             WebClient client = new WebClient();
            //client.DownloadFile("http://www.hao123.com%22,%22123.htm/");
            string reply = client.DownloadString("http://www.hao123.com/");
            Response.Write(reply);

    

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