您的位置:首页 > Web前端 > HTML

C# 获取网页html源文件

2013-01-11 18:16 483 查看
</pre><pre name="code" class="csharp">        /// <summary>
/// 获取网页html源文件
/// </summary>
/// <param name="url">网页地址</param>
/// <param name="encodingStr">网页文件编码字符串</param>
/// <returns>html源文件</returns>
public static string GetPageSource(string url, string encodingStr)
{
HttpWebResponse res = null;
string strResult = "";
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
//req.Method = "POST";
req.KeepAlive = true;
req.ContentType = "application/x-www-form-urlencoded";
req.Accept = "text/Html,application/xhtml+XML,application/xml;q=0.9,*/*;q=0.8";
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8";
res = (HttpWebResponse)req.GetResponse();
StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding(encodingStr));
while (reader.Peek() >= 0)
{
strResult += reader.ReadLine();
}
reader.Close();
reader.Dispose();
req.Abort();
res.Close();
res.Dispose();
}
catch
{

}
finally
{
if (res != null)
{
res.Close();
}
}
return strResult;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# html web