Tuesday, 26 July 2011

How to retrieve a webpage using ASP.NET 2.0 and VB .NET


This tutorial will show you how to retrieve an external webpage using the .NET System.Net class, ASP.NET 2.0 and VB.NET

The .NET Framework offers a number of types that makes accessing resources on the network easy.

To display an external webpage we will need to use the System.IO, System.Net, and System.Text namespaces.

Imports System.IO
Imports System.Net
Imports System.Text

Try Server Intellect for Windows Server Hosting. Quality and Quantity!

We'll put our code in the Page_Load() event.

When the Page_Load() event fires it instantiates a new WebRequest object with the URL that we wish to retrieve. We then execute the GetResponse() method of this new object which returns a WebResponse object. After this is complete it is simply a matter of executing the GetResponseStream() method of the WebResponse object and reading the stream that is returned.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim req As WebRequest = WebRequest.Create("http://www.google.com")
Dim resp As WebResponse = req.GetResponse()

Dim s As Stream = resp.GetResponseStream()
Dim sr As StreamReader = New StreamReader(s, Encoding.ASCII)
Dim doc As String = sr.ReadToEnd()

lblStatus.Text = doc
End Sub

Server Intellect offers Windows Hosting Dedicated Servers at affordable prices. I'm very pleased!

The front end .aspx page looks something like this:

<table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#5482fc">
<tr>
<td height="50" align="center" class="lgHeader1">How to Display Data using the DataList control ASP.NET
2.0 and C#</td>
</tr>
</table>
<br />
<table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#cccccc">
<tr>
<td width="100" align="right" bgcolor="#eeeeee" class="header1"> External WebPage:</td>
<td align="center" bgcolor="#FFFFFF">
&nbsp;
&nbsp;<asp:label ID="lblStatus" runat="server"></asp:label></td>
</tr>
</table>

I just signed up at Server Intellect and couldn't be more pleased with my Windows Server! Check it out and see for yourself.

The flow for the code behind page is as follows:

Imports System.IO
Imports System.Net
Imports System.Text
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim req As WebRequest = WebRequest.Create("http://www.google.com")
Dim resp As WebResponse = req.GetResponse()

Dim s As Stream = resp.GetResponseStream()
Dim sr As StreamReader = New StreamReader(s, Encoding.ASCII)
Dim doc As String = sr.ReadToEnd()

lblStatus.Text = doc
End Sub
End Class

Looking for the C#.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

No comments:

Post a Comment