【原创】 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>");
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值