您的位置:首页 > 理论基础 > 计算机网络

httpclient模拟登陆(使用js设置cookie)

2013-12-11 00:46 661 查看
最近做智能终端课的大程,要在android上利用httpclient模拟登陆学校的bbs,因为网络、html协议、脚本语言都还没学,所以查看了很多东西,可算弄出来了。

模拟登陆之前也做过,但是上次的bbs是通过服务器返回的响应(response)的header中set-cookie设置下次访问的cookie,在这种情况下httpclient是可以自动管理cookie的,因此只要先post登陆的表单,然后就可以访问要访问的网页。但这次*河蟹*的学校bbs是通过js来设置cookie的,这时就要自己设置httpclient的cookie。而且她喵的httpclient的前后兼容性不是很好,网上大多数都是基于httpclient
3.1版的,我在官网上找到的教程是4.3版,但android内嵌的httpclient是4.0版的(据说),害我弄了半天啊啊啊啊!!!3.1版的就不说了,就说说我在android(httpclient 4.0版)和在java se(4.3)上用的方法。

比如,学校bbs登陆成功后返回的信息

<html>
<meta http-equiv='Content-Type' content='text/html; charset=gb2312'>
<link rel=stylesheet type=text/css href='/bbs.css'>
<script>document.cookie='utmpnum=51;path=/;domain=.' + window.location.host</script>
<script>document.cookie='utmpkey=20154732;path=/;domain=.' + window.location.host</script>
<script>document.cookie='utmpuserid=yay;path=/;domain=.' + window.location.host</script>
<meta http-equiv='Refresh' content='0; url=/firstpage.php'>


h4ttpclient  4.3:

最简单的方法就是通过得到的cookie定制一个httpclient,根据上面的例子,方法如下:

CookieStore cookieStore =  new BasicCookieStore();

for (int i = 0; i < 3; i++) {
String name;
String value;
int flag=s.indexOf("document.cookie");
s=s.substring(flag+17);
flag=s.indexOf('=');
name=s.substring(0, flag);
value=s.substring(flag+1, s.indexOf(';'));
BasicClientCookie cookie = new BasicClientCookie(name,
value);
cookie.setVersion(0);
cookie.setDomain(".www.zju88.org");  //这个网址对应的是window.location.host的返回值
cookie.setPath("/");
cookieStore.addCookie(cookie);
}
// Set the store
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();


android:

我找了半天也没找到上面方法对应的API,只能在每次访问前加cookie了

String cookie="";
for (int i = 0; i < 3; i++) {
String name;
String value;
int flag=s.indexOf("document.cookie");
s=s.substring(flag+17);
flag=s.indexOf('=');
name=s.substring(0, flag);
value=s.substring(flag+1, s.indexOf(';'));
cookie +=name +"="+value;
if(i!=2)
cookie+=";";
}

/*
* 每次访问网络
*/
HttpGet httpget = new HttpGet(url);
httpget.addHeader("Cookie",cookie);
//如果httpclient中已经有cookie可能需要设置httpclient的cookie策略,具体可查官方API (:
HttpResponse response = httpclient.execute(httpget);

ps:如果是用java SE,也可以使用htmlunit类,它会执行js。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息