C#获取网页内容

发布时间:2009年06月04日      浏览次数:466 次
using System.Net;
using System.IO;
using System.Text;

//方法一:
// Create a request for the URL.
WebRequest request = WebRequest.Create("http://www.qqview.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);
// 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.qqview.com");
StreamReader reader = new StreamReader(data,Encoding.Default);
string s = reader.ReadToEnd();
Response.Write(s);
data.Close();
reader.Close();

//方法三:
WebClient client = new WebClient();
//client.DownloadFile("http://www.qqview.com","123.htm");
string reply = client.DownloadString("http://www.qqview.com");
Response.Write(reply);
免责声明:本站相关技术文章信息部分来自网络,目的主要是传播更多信息,如果您认为本站的某些信息侵犯了您的版权,请与我们联系,我们会即时妥善的处理,谢谢合作!