[asp.net]利用HttpRequest登录到某个网站,然后获取网站信息

问题:有的网站的相关内容必须要在登录后才可以查看,其登录信息保存在session变量之中。这样,使用asphttp等组件就难以正确得到所要的信息。

解决:使用asp.net中的httprequest和httpresponse来实现。

要点:
1。 通过附加一个cookiecontainer到httprequest对象中,可以得到登录后返回的代表SESSION ID的COOKIE。 见Login方法
2。 将此COOKIE包含在一个cookiecontainer中并附加到另一个HTTPREQUEST请求中,则可以实现SESSION的还原。见getPage方法

源程序如下:
getHttpInfo.aspx:
ExpandedBlockStart.gif ContractedBlock.gif <% dot.gif @ Page language="c#" Codebehind="getHttpInfo.aspx.cs" AutoEventWireup="false" Inherits="PdfTest.getHttpInfo"  %>
None.gif
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"  >
None.gif
< HTML >
None.gif    
< HEAD >
None.gif        
< title > WebForm1 </ title >
None.gif        
< meta  content ="Microsoft Visual Studio 7.0"  name ="GENERATOR" >
None.gif        
< meta  content ="C#"  name ="CODE_LANGUAGE" >
None.gif        
< meta  content ="JavaScript"  name ="vs_defaultClientScript" >
None.gif        
< meta  content ="http://schemas.microsoft.com/intellisense/ie5"  name ="vs_targetSchema" >
None.gif    
</ HEAD >
None.gif    
< body >
None.gif        
< form  id ="Form1"  method ="post"  runat ="server" >
None.gif        
</ form >
None.gif    
</ body >
None.gif
</ HTML >
None.gif
getHttpInfo.aspx.cs:
None.gif using  System;
None.gif
using  System.Collections;
None.gif
using  System.ComponentModel;
None.gif
using  System.Data;
None.gif
// using System.Data.OleDb;
None.gif
using  System.Drawing;
None.gif
using  System.Web;
None.gif
using  System.Web.SessionState;
None.gif
using  System.Web.UI;
None.gif
using  System.Web.UI.WebControls;
None.gif
using  System.Web.UI.HtmlControls;
None.gif
using  System.Net;
None.gif
using  System.IO;
None.gif
using  System.Text;
None.gif
using  System.Text.RegularExpressions;
None.gif
using  Microsoft.Data.Odbc;
None.gif
None.gif
namespace  PdfTest
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// Summary description for WebForm1.
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public class getHttpInfo : System.Web.UI.Page
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
protected static string cookieheader;
InBlock.gif
InBlock.gif    
InBlock.gif        
private void Page_Load(object sender, System.EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// Put user code to initialize the page here
InBlock.gif

InBlock.gif            
string strResult;
InBlock.gif
InBlock.gif            
if (HttpContext.Current.Application["cookieheader"!= null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                cookieheader 
= (string)HttpContext.Current.Application["cookieheader"];
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//Login into the website and keep the cookie for the session in the application variable
InBlock.gif
                string strLogin = Login("http://www.thesiteyouwanttovisit/theloginpage.asp""Action=&USERID=&Password=") ;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
InBlock.gif
InBlock.gif            strResult 
= getPage("http://www.thesiteyouwanttovisit/theloginpage.asp""Action=&data=") ;
InBlock.gif
InBlock.gif
InBlock.gif            
//Write the result to htm file
InBlock.gif
            FileStream htmFile = new FileStream("c:save.htm", FileMode.OpenOrCreate);
InBlock.gif            StreamWriter sw 
= new StreamWriter(htmFile);
InBlock.gif            sw.Write(strResult);
InBlock.gif            sw.Close();
InBlock.gif            htmFile.Close();
InBlock.gif
InBlock.gif            
// output the result
InBlock.gif
            Response.Write(strResult);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif
InBlock.gif        
public static string Login(String url, String paramList) 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            HttpWebResponse res 
= null;
InBlock.gif            
string strResult="";
InBlock.gif
InBlock.gif            
try 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif
InBlock.gif                HttpWebRequest req 
= (HttpWebRequest)WebRequest.Create(url);
InBlock.gif                req.Method 
= "POST";
InBlock.gif                req.ContentType 
= "application/x-www-form-urlencoded";
InBlock.gif                req.AllowAutoRedirect 
= false;
InBlock.gif                CookieContainer cookieCon 
= new CookieContainer();
InBlock.gif                req.CookieContainer 
= cookieCon;
InBlock.gif
InBlock.gif                StringBuilder UrlEncoded 
= new StringBuilder();
ExpandedSubBlockStart.gifContractedSubBlock.gif                Char[] reserved 
= dot.gif{'?''=''&'};
InBlock.gif                
byte[] SomeBytes = null;
InBlock.gif
InBlock.gif                
if (paramList != null
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
int i=0, j;
InBlock.gif                    
while(i<paramList.Length)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        j
=paramList.IndexOfAny(reserved, i);
InBlock.gif                        
if (j==-1)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length
-i)));
InBlock.gif                            
break;
ExpandedSubBlockEnd.gif                        }

InBlock.gif                        UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j
-i)));
InBlock.gif                        UrlEncoded.Append(paramList.Substring(j,
1));
InBlock.gif                        i 
= j+1;
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    SomeBytes 
= Encoding.UTF8.GetBytes(UrlEncoded.ToString());
InBlock.gif                    req.ContentLength 
= SomeBytes.Length;
InBlock.gif                    Stream newStream 
= req.GetRequestStream();
InBlock.gif                    newStream.Write(SomeBytes, 
0, SomeBytes.Length);
InBlock.gif                    newStream.Close();
ExpandedSubBlockEnd.gif                }
 
InBlock.gif                
else 
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    req.ContentLength 
= 0;
ExpandedSubBlockEnd.gif                }

InBlock.gif
InBlock.gif
InBlock.gif                res 
= (HttpWebResponse)req.GetResponse();
InBlock.gif                cookieheader 
= req.CookieContainer.GetCookieHeader(new Uri(url));
InBlock.gif                HttpContext.Current.Application.Lock();
InBlock.gif                HttpContext.Current.Application[
"cookieheader"= cookieheader;
InBlock.gif                HttpContext.Current.Application.UnLock();
InBlock.gif
InBlock.gif                Stream ReceiveStream 
= res.GetResponseStream();
InBlock.gif                Encoding encode 
= System.Text.Encoding.GetEncoding("utf-8");
InBlock.gif                StreamReader sr 
= new StreamReader( ReceiveStream, encode );
InBlock.gif                Char[] read 
= new Char[256];
InBlock.gif                
int count = sr.Read( read, 0256 );
InBlock.gif                
while (count > 0
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    String str 
= new String(read, 0, count);
InBlock.gif                    strResult 
+= str;
InBlock.gif                    count 
= sr.Read(read, 0256);
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }
 
InBlock.gif            
catch(Exception e) 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                strResult 
= e.ToString();
ExpandedSubBlockEnd.gif            }
 
InBlock.gif            
finally 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if ( res != null ) 
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    res.Close();
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
return strResult;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif
InBlock.gif        
public static string getPage(String url, String paramList) 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            HttpWebResponse res 
= null;
InBlock.gif            
string strResult = "";
InBlock.gif
InBlock.gif            
try 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif
InBlock.gif                HttpWebRequest req 
= (HttpWebRequest)WebRequest.Create(url);
InBlock.gif                req.Method 
= "POST";
InBlock.gif                req.KeepAlive 
= true;
InBlock.gif                req.ContentType 
= "application/x-www-form-urlencoded";
InBlock.gif                CookieContainer cookieCon 
= new CookieContainer();
InBlock.gif                req.CookieContainer 
= cookieCon;
InBlock.gif                req.CookieContainer.SetCookies(
new Uri(url),cookieheader);
InBlock.gif                StringBuilder UrlEncoded 
= new StringBuilder();
ExpandedSubBlockStart.gifContractedSubBlock.gif                Char[] reserved 
= dot.gif{'?''=''&'};
InBlock.gif                
byte[] SomeBytes = null;
InBlock.gif
InBlock.gif                
if (paramList != null
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
int i=0, j;
InBlock.gif                    
while(i<paramList.Length)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        j
=paramList.IndexOfAny(reserved, i);
InBlock.gif                        
if (j==-1)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length
-i)));
InBlock.gif                            
break;
ExpandedSubBlockEnd.gif                        }

InBlock.gif                        UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j
-i)));
InBlock.gif                        UrlEncoded.Append(paramList.Substring(j,
1));
InBlock.gif                        i 
= j+1;
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    SomeBytes 
= Encoding.UTF8.GetBytes(UrlEncoded.ToString());
InBlock.gif                    req.ContentLength 
= SomeBytes.Length;
InBlock.gif                    Stream newStream 
= req.GetRequestStream();
InBlock.gif                    newStream.Write(SomeBytes, 
0, SomeBytes.Length);
InBlock.gif                    newStream.Close();
ExpandedSubBlockEnd.gif                }
 
InBlock.gif                
else 
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    req.ContentLength 
= 0;
ExpandedSubBlockEnd.gif                }

InBlock.gif
InBlock.gif
InBlock.gif                res 
= (HttpWebResponse)req.GetResponse();
InBlock.gif                Stream ReceiveStream 
= res.GetResponseStream();
InBlock.gif                Encoding encode 
= System.Text.Encoding.GetEncoding("utf-8");
InBlock.gif                StreamReader sr 
= new StreamReader( ReceiveStream, encode );
InBlock.gif                Char[] read 
= new Char[256];
InBlock.gif                
int count = sr.Read( read, 0256 );
InBlock.gif                
while (count > 0
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    String str 
= new String(read, 0, count);
InBlock.gif                    strResult 
+= str;
InBlock.gif                    count 
= sr.Read(read, 0256);
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }
 
InBlock.gif            
catch(Exception e) 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                strResult 
= e.ToString();
ExpandedSubBlockEnd.gif            }
 
InBlock.gif            
finally 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if ( res != null ) 
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    res.Close();
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
return strResult;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
Web Form Designer generated code#region Web Form Designer generated code
InBlock.gif        
override protected void OnInit(EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//
InBlock.gif            
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
InBlock.gif            
//
InBlock.gif
            InitializeComponent();
InBlock.gif            
base.OnInit(e);
ExpandedSubBlockEnd.gif        }

InBlock.gif        
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Required method for Designer support - do not modify
InBlock.gif        
/// the contents of this method with the code editor.
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private void InitializeComponent()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{    
InBlock.gif            
this.Load += new System.EventHandler(this.Page_Load);
InBlock.gif
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
InBlock.gif        
InBlock.gif
InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

转载于:https://www.cnblogs.com/cai9911/archive/2006/10/17/531137.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值