C# 在採集資料時的驗證與登入處理

iDotNetSpace發表於2009-01-19

首先開啟網站,檢視原始檔,找到他的登入表單部分。

比如:


     
       
         
         
       
       
         
         
       
     
使用者名稱:
            maxlength="40" size="23" name="username" id="username" />
密 碼:
            maxlength="40" size="23" name="passwd" type="password" id="passwd" />


從以上表單可以看出,表單提交的方法是:POST,提交至loginMain.jsp處理,共有兩個表單項即:username、passwd

下面是C#模仿登入程式:Login.cs

using System;
using System.Data;
using System.Net;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

///
/// 登入網站並獲取Cookies
///
/// 成功登入的Cookie資訊
public static CookieContainer Get_Login()
{
             CookieContainer cc
= new CookieContainer();
            
string FormURL="http://blog.hnce.net/loginMain.jsp";                //處理表單的絕對URL地址
            string FormData = "username=slick&passwd=hedy12345";    //表單需要提交的引數,注意改為你已註冊的資訊。
             ASCIIEncoding encoding = new ASCIIEncoding();
            
byte[] data = encoding.GetBytes(FormData);

             HttpWebRequest request
= (HttpWebRequest)WebRequest.Create(FormURL);
             request.Method
= "POST";    //資料提交方式
             request.ContentType = "application/x-www-form-urlencoded";
             request.ContentLength
= data.Length;
             request.UserAgent
= "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)";
            
//模擬一個UserAgent
             Stream newStream = request.GetRequestStream();
             newStream.Write(data,
0, data.Length);

             newStream.Close();
                   
             request.CookieContainer
= cc;
                   
             HttpWebResponse response
= (HttpWebResponse)request.GetResponse();
             cc.Add(response.Cookies);
             Stream stream
= response.GetResponseStream();
            
string WebContent = new StreamReader(stream, System.Text.Encoding.Default).ReadToEnd();
            
return cc;
}



呼叫以上的方法來獲取需要登入才能檢視的內容。

             CookieContainer cc = new CookieContainer();
             cc
= Login.Get_Login();            //獲取登入Cookies

            
string PhotoClassURL = "http://blog.hnce.net/xxx.jsp";
             HttpWebRequest Myrequest
= (HttpWebRequest)WebRequest.Create(PhotoClassURL);
             Myrequest.CookieContainer
= cc;
             HttpWebResponse Myresponse
= (HttpWebResponse)Myrequest.GetResponse();
             cc.Add(Myresponse.Cookies);
             Stream Mystream
= Myresponse.GetResponseStream();
            
string sHtml = new StreamReader(Mystream, System.Text.Encoding.Default).ReadToEnd();



sHtml即為你登入之後看到的內容。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-541445/,如需轉載,請註明出處,否則將追究法律責任。

相關文章