62,620
社区成员
发帖
与我相关
我的任务
分享public void login() throws ClientProtocolException, IOException
{
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
//获取一个cookie
HttpGet httpget = new HttpGet("https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true");
try {
httpClient.execute(httpget);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpget.abort();
//获取登录要用到的token
String token=null;
HttpGet getToken = new HttpGet("https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true");
HttpResponse response = httpClient.execute(getToken);
HttpEntity entity = response.getEntity();
String html = HtmlTool.getHtml(entity);//一个函数打印entity没什么作用
Pattern tokenp=Pattern.compile("bdPass.api.params.login_token='(.*?)';");
Matcher m;
m = tokenp.matcher(html);
if(m.find()){
token=m.group(1);
}
System.out.println(token);
HttpPost httppost = new HttpPost("https://passport.baidu.com/v2/api/?login");
//构造登录请求post的数据
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("tpl", "mn"));
nvps.add(new BasicNameValuePair("callback", "parent.bdPass.api.login._postCallback"));
nvps.add(new BasicNameValuePair("staticpage", "https://passport.baidu.com/v3Jump.html"));
nvps.add(new BasicNameValuePair("codestring", ""));
nvps.add(new BasicNameValuePair("ppui_logintime", "10484"));
nvps.add(new BasicNameValuePair("u", "https://passport.baidu.com/"));
nvps.add(new BasicNameValuePair("charset", "utf-8"));
nvps.add(new BasicNameValuePair("index", "0"));
nvps.add(new BasicNameValuePair("password", "密码"));
nvps.add(new BasicNameValuePair("loginType", "1"));
nvps.add(new BasicNameValuePair("safeflg", "0"));
nvps.add(new BasicNameValuePair("isphone", "false"));
nvps.add(new BasicNameValuePair("username", "用户名"));
nvps.add(new BasicNameValuePair("verifycode", ""));
nvps.add(new BasicNameValuePair("mem_pass", "on"));
httppost.setHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)");
httppost.setHeader("Host","passport.baidu.com");
nvps.add(new BasicNameValuePair("token", token));//得到的token
nvps.add(new BasicNameValuePair("class", "login"));
nvps.add(new BasicNameValuePair("tangram", "true"));
httppost.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
HttpResponse response2 = httpClient.execute(httppost);
String ss = HtmlTool.getHtml(response2.getEntity());
System.out.println(ss);