模拟登陆的原理很简单,就是发送一个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();
}
|
可以看到我已经进入了后台了:
如果我是没有登陆的情况下进入这个地址是这样的:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。