模擬登陸的原理很簡(jiǎn)單,就是發(fā)送一個(gè)http 請(qǐng)求服務(wù)器獲得響應(yīng),然后客戶端獲取到cookie即可實(shí)現(xiàn)模擬登陸,比如一些搶票軟件的原理無(wú)非也是這樣模擬客戶端的cookie 然后發(fā)送請(qǐng)求去搶票,然后12306 本文將演示如何用c# 來(lái)實(shí)現(xiàn)模擬登陸的,推薦一款工具fiddler,這是一款監(jiān)聽(tīng)http 請(qǐng)求的利器。廢話不多說(shuō),我就以博客園為例來(lái)實(shí)現(xiàn)模擬登陸。首先我登陸博客園 http://passport.cnblogs.com/login.aspx 輸入用戶名和密碼點(diǎn)登陸 就會(huì)看到fiddler 上的相關(guān)信息:
ok,我首先需要發(fā)送一個(gè)http 請(qǐng)求 ,這個(gè)請(qǐng)求時(shí)post的方式,然后用戶名和密碼就是post的數(shù)據(jù)。代碼如下:
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); //創(chuàng)建http 請(qǐng)求 httprequset.cookiecontainer = cookie; //設(shè)置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" ; //以上信息在監(jiān)聽(tīng)請(qǐng)求的時(shí)候都有的直接復(fù)制過(guò)來(lái) 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數(shù)據(jù)的寫入 httpwebresponse httpresponse = (httpwebresponse)httprequset.getresponse(); //獲得 服務(wù)端響應(yīng) return cookie; //拿到cookie } |
拿到cookie 之后我們就可以以用戶的什么去用戶的后臺(tái)或者其他的地方:
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 下面是調(diào)用 我寫的是一個(gè)控制臺(tái)程序:
1
2
3
4
5
6
7
8
9
|
static void main( string [] args) { string loginstr = "{要post 的登陸數(shù)據(jù)包括用戶名和密碼}" ; //從登陸的地址獲取cookie cookiecontainer cookie = getcookie(loginstr, "http://passport.cnblogs.com/login.aspx" ); //這個(gè)是進(jìn)入后臺(tái)地址 console.writeline(getcontent(cookie, "http://i.cnblogs.com/editposts.aspx" )); console.read(); } |
可以看到我已經(jīng)進(jìn)入了后臺(tái)了:
如果我是沒(méi)有登陸的情況下進(jìn)入這個(gè)地址是這樣的:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。