带cookie访问服务器实现模拟登录

        

2016-12-29

当我们需要抓取需要登录的网站的信息或者实现模拟登录时,我们需要得到第一次登录网站的cookie,以便于下次登录可以不用post参数实现登录,只要将cookie放入头文件就好,这是之前写的模拟登录学校教务的代码,记录以便查阅。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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;
}