程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> HttpRequest獲取網站信息的程序示例

HttpRequest獲取網站信息的程序示例

編輯:.NET實例教程

問題:有的網站的相關內容必須要在登錄後才可以查看,其登錄信息保存在session變量之中。這樣,使用ASPhttp等組件就難以正確得到所要的信息。

解決:使用ASP.Net中的httprequest和httpresponse來實現。

要點:
1。 通過附加一個cookiecontainer到httprequest對象中,可以得到登錄後返回的代表SESSION ID的COOKIE。 見Login方法
2。 將此COOKIE包含在一個cookIEcontainer中並附加到另一個HTTPREQUEST請求中,則可以實現SESSION的還原。見getPage方法

源程序如下:

getHttpInfo.ASPx:
<%@ Page language="c#" Codebehind="getHttpInfo.ASPx.cs" AutoEventWireup="false" Inherits="PdfTest.getHttpInfo" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD Html 4.0 Transitional//EN" >
<Html>
<HEAD>
<title>WebForm1</title>
<meta content="Microsoft Visual Studio 7.0" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClIEntScript">
<meta content="http://schemas.microsoft.com/intellisense/IE5" name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
</form>
</body>
</Html>


getHttpInfo.ASPx.cs:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
//using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Data.Odbc;

namespace PdfTest
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class getHttpInfo : System.Web.UI.Page
{
protected static string cookIEheader;


private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here

string strResult;

if (HttpContext.Current.Application["cookIEheader"] != null)
{
cookieheader = (string)HttpContext.Current.Application["cookIEheader"];
}
else
{
//Login into the website and keep the cookIE for the session in the application variable
string strLogin = Login("http://www.thesiteyouwanttovisit/theloginpage.ASP", "Action=&USERID=&PassWord=") ;
}


strResult = getPage("http://www.thesiteyouwanttovisit/theloginpage.ASP", "Action=&data=") ;


//Write the result to htm file
FileStream htmFile = new FileStream("c:\save.htm", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(htmFile);
sw.Write(strResult);
sw.Close();
htmFile.Close();

// output the result
Response.Write(strResult);
}


public static string Login(String url, String paramList)
{
HttpWebResponse res = null;
string strResult="";

try
{

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.AllowAutoRedirect = false;
CookieContainer cookieCon = new CookIEContainer();
req.CookieContainer = cookIECon;

StringBuilder UrlEncoded = new StringBuilder();
Char[] reserved = {'?', '=', '&'};
byte[] SomeBytes = null;

if (paramList != null)
{
int i=0, j;
while(i<paramList.Length)
{
j=paramList.IndexOfAny(reserved, i);
if (j==-1)
{
UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length-i)));
break;
}
UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j-i)));
UrlEncoded.Append(paramList.Substring(j,1));
i = j+1;
}
SomeBytes = Encoding.UTF8.GetBytes(UrlEncoded.ToString());
req.ContentLength = SomeBytes.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(SomeBytes, 0, SomeBytes.Length);
newStream.Close();
}
else
{
req.ContentLength = 0;
}


res = (HttpWebResponse)req.GetResponse();
cookieheader = req.CookieContainer.GetCookIEHeader(new Uri(url));
HttpContext.Current.Application.Lock();
HttpContext.Current.Application["cookieheader"] = cookIEheader;
HttpContext.Current.Application.UnLock();

Stream ReceiveStream = res.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader sr = new StreamReader( ReceiveStream, encode );
Char[] read = new Char[256];
int count = sr.Read( read, 0, 256 );
while (count > 0)
{
String str = new String(read, 0, count);
strResult += str;
count = sr.Read(read, 0, 256);
}
}
catch(Exception e)
{
strResult = e.ToString();
}
finally
{
if ( res != null )
{
res.Close();
}
}

return strResult;
}


public static string getPage(String url, String paramList)
{
HttpWebResponse res = null;
string strResult = "";

try
{

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.KeepAlive = true;
req.ContentType = "application/x-www-form-urlencoded";
CookieContainer cookieCon = new CookIEContainer();
req.CookieContainer = cookIECon;
req.CookieContainer.SetCookies(new Uri(url),cookIEheader);
StringBuilder UrlEncoded = new StringBuilder();
Char[] reserved = {'?', '=', '&'};
byte[] SomeBytes = null;

if (paramList != null)
{
int i=0, j;
while(i<paramList.Length)
{
j=paramList.IndexOfAny(reserved, i);
if (j==-1)
{
UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length-i)));
break;
}
UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j-i)));
UrlEncoded.Append(paramList.Substring(j,1));
i = j+1;
}
SomeBytes = Encoding.UTF8.GetBytes(UrlEncoded.ToString());
req.ContentLength = SomeBytes.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(SomeBytes, 0, SomeBytes.Length);
newStream.Close();
}
else
{
req.ContentLength = 0;
}


res = (HttpWebResponse)req.GetResponse();
Stream ReceiveStream = res.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader sr = new StreamReader( ReceiveStream, encode );
Char[] read = new Char[256];
int count = sr.Read( read, 0, 256 );
while (count > 0)
{
String str = new String(read, 0, count);
strResult += str;
count = sr.Read(read, 0, 256);
}
}
catch(Exception e)
{
strResult = e.ToString();
}
finally
{
if ( res != null )
{
res.Close();
}
}

return strResult;
}


#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.Net Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

 

}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved