模擬登陸的原理很簡單,就是發送一個http 請求服務器獲得響應,然后客戶端獲取到cookie即可實現模擬登陸,比如一些搶票軟件的原理無非也是這樣模擬客戶端的cookie 然后發送請求去搶票,然后12306 本文將演示如何用c# 來實現模擬登陸的,推薦一款工具fiddler,這是一款監聽http 請求的利器。廢話不多說,我就以博客園為例來實現模擬登陸。首先我登陸博客園 http://passport.cnblogs.com/login.aspx 輸入用戶名和密碼點登陸 就會看到fiddler 上的相關信息:
ok,我首先需要發送一個http 請求 ,這個請求時post的方式,然后用戶名和密碼就是post的數據。代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
static cookiecontainer getcookie( string poststring, string posturl) { cookiecontainer cookie = new cookiecontainer(); httpwebrequest httprequset = (httpwebrequest)httpwebrequest.create(posturl); //創建http 請求 httprequset.cookiecontainer = cookie; //設置cookie httprequset.method = "post" ; //post 提交 httprequset.keepalive = true ; httprequset.useragent = "mozilla/5.0 (windows nt 6.3; wow64; trident/7.0; rv:11.0) like gecko" ; httprequset.accept = "text/html, application/xhtml+xml, */*" ; httprequset.contenttype = "application/x-www-form-urlencoded" ; //以上信息在監聽請求的時候都有的直接復制過來 byte [] bytes = system.text.encoding.utf8.getbytes(poststring); httprequset.contentlength = bytes.length; stream stream = httprequset.getrequeststream(); stream.write(bytes, 0, bytes.length); stream.close(); //以上是post數據的寫入 httpwebresponse httpresponse = (httpwebresponse)httprequset.getresponse(); //獲得 服務端響應 return cookie; //拿到cookie } |
拿到cookie 之后我們就可以以用戶的什么去用戶的后臺或者其他的地方:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
static string getcontent(cookiecontainer cookie, string url) { string content; httpwebrequest httprequest = (httpwebrequest)httpwebrequest.create(url); httprequest.cookiecontainer = cookie; httprequest.referer = url; httprequest.useragent = "mozilla/5.0 (windows nt 6.3; wow64; trident/7.0; rv:11.0) like gecko" ; httprequest.accept = "text/html, application/xhtml+xml, */*" ; httprequest.contenttype = "application/x-www-form-urlencoded" ; httprequest.method = "get" ; httpwebresponse httpresponse = (httpwebresponse)httprequest.getresponse(); using (stream responsestream = httpresponse.getresponsestream()) { using (streamreader sr = new streamreader(responsestream, system.text.encoding.utf8)) { content = sr.readtoend(); } } return content; } |
ok 下面是調用 我寫的是一個控制臺程序:
1
2
3
4
5
6
7
8
9
|
static void main( string [] args) { string loginstr = "{要post 的登陸數據包括用戶名和密碼}" ; //從登陸的地址獲取cookie cookiecontainer cookie = getcookie(loginstr, "http://passport.cnblogs.com/login.aspx" ); //這個是進入后臺地址 console.writeline(getcontent(cookie, "http://i.cnblogs.com/editposts.aspx" )); console.read(); } |
可以看到我已經進入了后臺了:
如果我是沒有登陸的情況下進入這個地址是這樣的:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。