你登陆论坛的时候,我们先看看浏览器干了什么事儿:
用Firefox打开HiPda 的登陆页面,输入用户名和密码,点登陆。
下面是通过firebug插件获取的数据:
可以看到浏览器这个http://www.hi-pda.com/forum/logging.php?action=login&loginsubmit=yes&inajax=1网址发了一个POST请求
看一下它POST的参数是什么:
可以看到一共有7个参数:
第一个cookietime=259200,这个是固定的,直接传这个值过去就行;
第二个formhash是discuz论坛的一个设置,值在当前页面的源码里。
比如我们看一下网页的源码,搜一下formhash跟这里的formhash是不是一样的:
刚好是一样的。
第三个值loginfield是固定的,等于username;
第四个是你输入法密码;
第五个是安全提问的编号,由于我们没有选安全提问的问题,所以编号为0;
第六个referer,直接输进去这个就行;
第七个是你的用户名。
下面我们用代码实现自动登录。
首先通过上面的分析,首先需要formhash的值,这个我们可以通过HttpGet得到网页的源码,把formhash解析出来。
HttpClient httpClient = new DefaultHttpClient();
//得到网页的formhash值,用Jsoup解析出来
HttpGet httpGet = new HttpGet("http://www.hi-pda.com/forum/logging.php?action=login");
try{
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
String s = EntityUtils.toString(httpEntity,"GBK");
Element formhash_Element = Jsoup.parse(s).select("input[name=formhash]").first();
formhash = formhash_Element.attr("value");
System.out.println(formhash);
}
catch(Exception e ){
}
下面我们就可以登陆了,用HttpPost:
HttpPost httpPost=new HttpPost("http://www.hi-pda.com/forum/logging.php?action=login&loginsubmit=yes&inajax=1");
List<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("formhash",formhash));
params.add(new BasicNameValuePair("loginfield","username"));
params.add(new BasicNameValuePair("password","******"));
params.add(new BasicNameValuePair("questionid","0"));
params.add(new BasicNameValuePair("referer","http://www.hi-pda.com/forum/index.php"));
params.add(new BasicNameValuePair("username","******"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "GBK"));
HttpResponse response=httpClient.execute(httpPost);
HttpEntity entity=response.getEntity();
String ans=EntityUtils.toString(entity);
}catch (Exception e){
}
现在我们已经登陆成功了,只要用同一个HttpClient对象,就会一直显示登录状态。比如我们用这个httpClient打开一下D版试一下:
HttpGet getHome = new HttpGet("http://www.hi-pda.com/forum/index.php");
try{
httpClient.execute(getHome);
}catch (Exception e){
}
HttpGet getD=new HttpGet("http://www.hi-pda.com/forum/forumdisplay.php?fid=2");
try {
HttpResponse responseD = httpClient.execute(getD);
HttpEntity entityD=responseD.getEntity();
String str=EntityUtils.toString(entityD,"GBK");
System.out.println(str);
}catch (Exception e){
}
可以看到显示的是已登陆的D版的内容。