日期:2012-08-22  浏览次数:20397 次

 
Author
Date of Submission
User Level
Kareem Bawala
04/04/2001
Beginner
This is a simple application that the gets the source of a webpage via the WebRequest Object.

The WebRequest class is defined in System.Net namespace. WebRequest is an abstract class. It is the base class for accessing data from the internet in the .Net Framework.
This tutorial would show you how to access data on the internet using the WebRequest Class.
Adding namespace Reference

Since the WebRequest class is defined in the System.Net namespace, so the first thing to do is to Add the System.Net reference to the project.

using System.Net;

Creating the WebRequest Object

The WebRequest Object should not be created directly. It is an abstract object. To create the WebRequest you should use the WebRequestFactory object. The WebRequestFactory class is a static class that returns an instance of an object derived from WebRequest.

You use the create method of the WebRequestFactory class. Here is an example:

// You could pass the create method a string or a URI
WebRequest WReq = WebRequestFactory.Create("http://www.yahoo.com");

OR

URI uriWebSite = new URI("http://www.yahoo.com");
WebRequest WReq = WebRequestFactory.Create(uriWebSite);

To get the response from the server you call the GetResponse() Method on the WebRequest object.
WebResponse wResp = WReq.GetResponse();

Getting the Stream of Data from the WebResponse Object

Getting the Stream of data you use the GetResponseStream() Method on the WebResponse Object and you specify how you want to encode the data you are getting back.
StreamReader sr = new StreamReader(WResp.GetResponseStream(), Encoding.ASCII);

That's it folks.
namespace HTMLSourceViewer {
using System;
using System.Net;
using System.Text;
using System.IO;
using System.WinForms;
public class GetWebPageSource
{
public GetWebPageSource() { }
public GetWebPageSource(string webAddress)
{
        this. webAddress = webAddress;
}
public string GetSource()
{
       StringBuilder strSource = new StringBuilder("");
try
{
       WebRequest WReq = WebRequestFactory.Create(this.webAddress);
       WebResponse WResp = WReq.GetResponse();
       // get the stream of data
       StreamReader sr = new StreamReader(WResp.GetResponseStream(), Encoding.ASCII);
       string strTemp = "";
        while ((strTemp = sr.ReadLine()) != null)
        {
              strSource.Append(strTemp + "\r\n");
        }
        sr.Close();
}
catch (WebException WebExcp)
{
       MessageBox.Show(WebExcp.Message, "Error", MessageBox.IconError);
}
return strSource.ToString();
}
  
// Accessor method
public void setWebAddress(string strNewAddress)
{
this.webAddress = strNewAddress;
}
// private variables
private string webAddress;
}
}
namespace HTMLSourceViewer
{
using System;
  
using System.Drawing;

using System.Collections;
  
using System.ComponentModel;
 &