geturlhtml.aspx
<%@ page language=”c#” codebehind=”geturlhtml.aspx.cs” src=”geturlhtml.aspx.cs” autoeventwireup=”false” inherits=”lion.web.forum.webform1″ %>
<html>
<head>
<title>lion互动网络=>利用webclient和webrequest类获得网页源代码</title>
<meta http-equiv=”content-type” content=”text/html; charset=gb2312″>
</head>
<body>
<form runat=”server”>
<asp:textbox id=”urltext” runat=”server” width=”50%”>http://www.lionsky.net/mywebsite/index.aspx</asp:textbox>
<asp:button id=”button1″ runat=”server” text=”用webclient得到”></asp:button>
<asp:button id=”button2″ runat=”server” text=”用webrequest得到”></asp:button><br>
<asp:textbox id=”contenthtml” runat=”server” width=”100%” height=”360px” textmode=”multiline”></asp:textbox>
</form>
</body>
</html>
geturlhtml.aspx.cs
using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.drawing;
using system.web;
using system.web.sessionstate;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
namespace lion.web.forum
{
/// <summary>
/// webform1 的摘要说明。
/// </summary>
public class webform1 : system.web.ui.page
{
protected system.web.ui.webcontrols.textbox textbox1;
protected system.web.ui.webcontrols.button button1;
protected system.web.ui.webcontrols.button button2;
protected system.web.ui.webcontrols.textbox urltext;
protected system.web.ui.webcontrols.textbox contenthtml;
protected system.web.ui.webcontrols.textbox textbox2;
#region web 窗体设计器生成的代码
override protected void oninit(eventargs e)
{
//
// codegen: 该调用是 asp.net web 窗体设计器所必需的。
//
initializecomponent();
base.oninit(e);
}
/// <summary>
/// 设计器支持所需的方法 – 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void initializecomponent()
{
this.button1.click += new system.eventhandler(this.button1_click);
this.button2.click += new system.eventhandler(this.button2_click);
}
#endregion
private void button1_click(object sender, system.eventargs e)
{
string pageurl = urltext.text;
system.net.webclient wc = new system.net.webclient();
wc.credentials = system.net.credentialcache.defaultcredentials;
///方法一:
byte[] pagedata = wc.downloaddata(pageurl);
contenthtml.text = system.text.encoding.default.getstring(pagedata);
/// 方法二:
/// ***************代码开始**********
/// stream resstream = wc.openread(pageurl);
/// streamreader sr = new streamreader(resstream,system.text.encoding.default);
/// contenthtml.text = sr.readtoend();
/// resstream.close();
/// **************代码结束********
///
wc.dispose();
}
private void button2_click(object sender, system.eventargs e)
{
string pageurl = urltext.text;
system.net.webrequest request = system.net.webrequest.create(pageurl);
system.net.webresponse response = request.getresponse();
system.io.stream resstream = response.getresponsestream();
system.io.streamreader sr = new system.io.streamreader(resstream, system.text.encoding.default);
contenthtml.text = sr.readtoend();
resstream.close();
sr.close();
}
}
}
