【原创】 ASP.NET C# 远程获取WEB页源代码
try
{
//方法一
HttpWebRequest webrq = WebRequest.Create("http://www.hiyours.com.cn/index.aspx") as HttpWebRequest;
HttpWebResponse webrs = webrq.GetResponse() as HttpWebResponse;
StreamReader sr = new StreamReader(webrs.GetResponseStream(), Encoding.GetEncoding("gb2312"));
Localize1.Text = Server.HtmlEncode(Regex.Match(sr.ReadToEnd(), "<body[\\s\\S]*?</body>", RegexOptions.IgnoreCase).Value);
//方法二
using (WebClient client = new WebClient())
{
client.Headers.Set("User-Agent", "Microsoft Internet Explorer");//此句是关键
Byte[] pageData = client.DownloadData("http://www.hiyours.com.cn/index.aspx");
Localize1.Text = Server.HtmlEncode(Encoding.GetEncoding("gb2312").GetString(pageData));
}
//方法三 只能用于静态读取字符串
using (StreamReader sr = new StreamReader(Server.MapPath("d.aspx"), Encoding.GetEncoding("gb2312"))) //模板页路径
{
Localize1.Text = Server.HtmlEncode(sr.ReadToEnd());
sr.Close();
}
}
catch
{
Response.Write("<Script>alert('读取文件错误')</Script>");
}