using System.Net;
using System.IO;
/// <summary>
/// 根据Url获取页面所有内容
/// </summary>
/// <param name="URL">请求的url</param>
/// <returns>返回页面的内容</returns>
public string GetContentFromUrl(string URL)
{
try
{
string strBuff = "";
int byteRead = 0;
char[] cbuffer = new char[256];
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(URL));
HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
Stream respStream = httpResp.GetResponseStream();
StreamReader respStreamReader = new StreamReader(respStream, System.Text.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();
return strBuff;
}
catch (Exception ex)
{
return ex.Message;
}
}
方法二:
using System.Net;
/// <summary>
/// 根据Url获取页面所有内容
/// </summary>
/// <param name="url">请求的url</param>
/// <returns>返回页面的内容</returns>
public string GetContentFromUrl(string url)
{
try
{
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;//获取或设置请求凭据
Byte[] pageData = client.DownloadData(url); //下载数据
string pageHtml = System.Text.Encoding.UTF8.GetString(pageData);
return pageHtml;
}
catch (WebException ex)
{
return ex.Message;
}
}