public static ArrayList<String> login(String email,String password,String captcha_solution,String captcha_id) throws Exception{
// 1.客户端(网站B) 需要在豆瓣上申请一个 apiKey apisecret 程序员申请的,可以使用程序员自己的账号申请
// 作用:让豆瓣能够知道 请求来源于哪个客户端
String apiKey = "0fdb2fe6489d158a2f918fb3g5h5d";
String secret = "c1af297c30d54927";
DoubanService myService = new DoubanService("我的豆瓣客户端", apiKey, secret);
// 2.拿着刚才申请的key 去豆瓣 换取一个新的认证的钥匙
// 参数是代表的认证完毕后的返回的url的路径
// 如果身份认证后 想完成页面的重定向 就可以设置url的参数
String authurl = myService.getAuthorizationUrl(null);
System.out.println("认证的url为:" + authurl);
// TODO:采用http协议 模拟用户访问 authurl 地址
// 模拟登陆豆瓣的服务器获取登陆成功的cookies
// post请求的地址 http://www.douban.com/accounts/login
// post提交的数据
// 创建一个http的浏览器
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.douban.com/accounts/login");
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("source", "simple"));
parameters
.add(new BasicNameValuePair("redir", "http://www.douban.com"));
parameters.add(new BasicNameValuePair("form_email",
email));
parameters.add(new BasicNameValuePair("form_password", password));
if((captcha_id != null)&&(captcha_solution != null)){
parameters.add(new BasicNameValuePair("captcha-solution", captcha_solution));
parameters.add(new BasicNameValuePair("captcha-id", captcha_id));
}
parameters.add(new BasicNameValuePair("user_login", "登陆"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
"UTF-8");
post.setEntity(entity);
// 拿着浏览器 提交post请求
HttpResponse response = client.execute(post);
System.out.println("状态码:" + response.getStatusLine().getStatusCode());
CookieStore cookies = client.getCookieStore(); // 把登陆成功的cookie获取出来.
// 模拟用户点击同意的post请求
DefaultHttpClient newClient = new DefaultHttpClient();
// 把刚才登陆成功的cookie设置给新打开的浏览器
newClient.setCookieStore(cookies);
HttpPost agreePost = new HttpPost(authurl);
int start = authurl.lastIndexOf("=") + 1;
List<BasicNameValuePair> agreeParams = new ArrayList<BasicNameValuePair>();
agreeParams.add(new BasicNameValuePair("ck", "DuX5"));
agreeParams.add(new BasicNameValuePair("oauth_token", authurl
.substring(start, authurl.length())));
agreeParams.add(new BasicNameValuePair("oauth_callback", ""));
agreeParams.add(new BasicNameValuePair("ssid", "7e51ec7f"));
agreeParams.add(new BasicNameValuePair("confirm", "同意"));
UrlEncodedFormEntity agreeentity = new UrlEncodedFormEntity(
agreeParams, "UTF-8");
agreePost.setEntity(agreeentity);
// 模拟了用户点击同意的操作
newClient.execute(agreePost);
// 4.如果用户点击了同意授权, 豆瓣的网址 就会给我们的应用程序 提供一个后门
// 后门还带了两把钥匙.
ArrayList<String> tokens = myService.getAccessToken();
System.out.println("access token:" + tokens.get(0));
System.out.println("token secret:" + tokens.get(1));
return tokens;
}
oauth认证----豆瓣客户端
最新推荐文章于 2021-06-06 20:48:42 发布