使用C#發送Http 請求實現模擬登陸(以博客園為例)


   

    模擬登陸的原理很簡單,就是發送一個Http 請求服務器獲得響應,然后客戶端獲取到cookie即可實現模擬登陸,比如一些搶票軟件的原理無非也是這樣模擬客戶端的cookie 然后發送請求去搶票。 本文將演示如何用C# 來實現模擬登陸的,推薦一款工具Fiddler,這是一款監聽http 請求的利器。廢話不多說,我就以博客園為例來實現模擬登陸。首先我登陸博客園 http://passport.cnblogs.com/login.aspx 輸入用戶名和密碼點登陸 就會看到Fiddler 上的相關信息:


Ok,我首先需要發送一個http 請求 ,這個請求時POST的方式,然后用戶名和密碼就是POST的數據。代碼如下:

 1 static CookieContainer GetCookie(string postString, string postUrl)
 2 {
 3 
 4 CookieContainer cookie = new CookieContainer();
 5 
 6 HttpWebRequest httpRequset = (HttpWebRequest)HttpWebRequest.Create(postUrl);//創建http 請求
 7 httpRequset.CookieContainer = cookie;//設置cookie
 8 httpRequset.Method = "POST";//POST 提交
 9 httpRequset.KeepAlive = true;
10 httpRequset.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko";
11 httpRequset.Accept = "text/html, application/xhtml+xml, */*";
12 httpRequset.ContentType = "application/x-www-form-urlencoded";//以上信息在監聽請求的時候都有的直接復制過來
13 byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postString);
14 httpRequset.ContentLength = bytes.Length;
15 Stream stream = httpRequset.GetRequestStream();
16 stream.Write(bytes, 0, bytes.Length);
17 stream.Close();//以上是POST數據的寫入
18 
19 HttpWebResponse httpResponse = (HttpWebResponse)httpRequset.GetResponse();//獲得 服務端響應
20 return cookie;//拿到cookie
21 }

 

拿到cookie 之后我們就可以以用戶的什么去用戶的后台或者其他的地方:

 1 static string GetContent(CookieContainer cookie, string url)
 2 {
 3 string content;
 4 HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
 5 httpRequest.CookieContainer = cookie;
 6 httpRequest.Referer = url;
 7 httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko";
 8 httpRequest.Accept = "text/html, application/xhtml+xml, */*";
 9 httpRequest.ContentType = "application/x-www-form-urlencoded";
10 httpRequest.Method = "GET";
11 
12 HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
13 
14 using (Stream responsestream = httpResponse.GetResponseStream())
15 {
16 
17 using (StreamReader sr = new StreamReader(responsestream, System.Text.Encoding.UTF8))
18 {
19 content = sr.ReadToEnd();
20 }
21 }
22 
23 return content;
24 }

 

OK 下面是調用 我寫的是一個控制台程序:

 1  1 static void Main(string[] args)
 2  2 {
 3  3 string loginstr = "{要post 的登陸數據包括用戶名和密碼}";
 4  4 
 5  5 //從登陸的地址獲取cookie
 6  6 CookieContainer cookie = GetCookie(loginstr, "http://passport.cnblogs.com/login.aspx");
 7  7 
 8  8 //這個是進入后台地址
 9  9 Console.WriteLine(GetContent(cookie, "http://i.cnblogs.com/EditPosts.aspx"));
10 10 
11 11 Console.Read();
12 12 }

 

可以看到我已經進入了后台了:

 

如果我是沒有登陸的情況下進入這個地址是這樣的:

 

下次我就寫一下怎么在模擬登陸之后發送http 請求實現添加刪除這些效果。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM