当我们需要抓取需要登录的网站的信息或者实现模拟登录时,我们需要得到第一次登录网站的cookie,以便于下次登录可以不用post参数实现登录,只要将cookie放入头文件就好,这是之前写的模拟登录学校教务的代码,记录以便查阅。
public String DoLogin(final String user, final String password, final String verifation) {
DefaultHttpClient defaultclient = new DefaultHttpClient();
//设置post参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("groupId", ""));
params.add(new BasicNameValuePair("j_username", user));
params.add(new BasicNameValuePair("j_password", password));
params.add(new BasicNameValuePair("j_captcha", verifation));
params.add(new BasicNameValuePair("login", "登录"));
//获得个人主界面的HTML
try {
HttpPost httpPost = new HttpPost(LOGINURL);
System.out.println(LOGINURL);
httpPost.setHeader("Cookie", Cookie);
HttpResponse httpResponse;
httpPost.setEntity((HttpEntity) new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpResponse = defaultclient.execute(httpPost);
httpPost.setHeader("Cookie", Cookie);
System.out.println(Cookie);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
StringBuffer sb = new StringBuffer();
HttpEntity entity = httpResponse.getEntity();
MAINBODYHTML = EntityUtils.toString(entity);
}
if(httpResponse.getStatusLine().getStatusCode() == 302){
String locationUrl=httpResponse.getLastHeader("Location").getValue();
System.out.println(locationUrl);
LOGINURL=locationUrl;
System.out.println("302");
DoLogin(user, password, verifation);
}
else{
StringBuffer sb = new StringBuffer();
HttpEntity entity = httpResponse.getEntity();
MAINBODYHTML = EntityUtils.toString(entity);
System.out.println( MAINBODYHTML);
}
} catch (UnsupportedEncodingException e) {
System.out.println("验证码不正确");
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LOGINURL="http://jw.djtu.edu.cn/academic/j_acegi_security_check";
return MAINBODYHTML;
}