第一篇博客。
前段时间研究新浪微博开发,发现官方提供的SDK(java版)里获取AccessToken竟然需要手动从浏览器中复制code到命令行下才能获取AccesToken,明显很不友好啊,网上也没找到切实可行的办法,只能自己研究,用HttpClient写了个自动获取的方法,代码如下:
public AccessToken getAccessToken() throws WeiboException, IOException {
Oauth oauth = new Oauth();
String url="https://api.weibo.com/oauth2/authorize";
HttpClient httpClient=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
AccessToken accessToken=null;
//初始化post数据
List<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userId", "微博账号"));
params.add(new BasicNameValuePair("passwd", "密码"));
params.add(new BasicNameValuePair("action", "login"));
params.add(new BasicNameValuePair("display", "default"));
params.add(new BasicNameValuePair("withOfficalFlag", "0"));
params.add(new BasicNameValuePair("withOfficalAccount", ""));
params.add(new BasicNameValuePair("scope", ""));
params.add(new BasicNameValuePair("ticket", ""));
params.add(new BasicNameValuePair("isLoginSina", ""));
params.add(new BasicNameValuePair("response_type", "code"));
params.add(new BasicNameValuePair("regCallback", "https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D3616023689%26response_type%3Dcode%26display%3Ddefault%26redirect_uri%3Dhttp%3A%2F%2F127.0.0.1%26from%3D%26with_cookie%3D"));
params.add(new BasicNameValuePair("redirect_uri", "http://127.0.0.1"));
params.add(new BasicNameValuePair("client_id", "3616023689"));
params.add(new BasicNameValuePair("appkey62", "5Pph2h"));
params.add(new BasicNameValuePair("state", ""));
params.add(new BasicNameValuePair("verifyToken", "null"));
params.add(new BasicNameValuePair("from", ""));
UrlEncodedFormEntity entity;
entity=new UrlEncodedFormEntity(params,"utf-8");
post.setEntity(entity);
post.addHeader("Referer", "https://api.weibo.com/oauth2/authorize?client_id=3616023689&redirect_uri=http://127.0.0.1&response_type=code&state=&scope=");
HttpResponse response=httpClient.execute(post);
String[] location=response.getLastHeader("Location").toString().split("=");
String code=null;
if(location.length>1){
code=location[1];
Log.logInfo("Code:"+code);
}
if(code!=null){
accessToken=oauth.getAccessTokenByCode(code);
Log.logInfo("Access_Token:"+accessToken.getAccessToken());
}
return accessToken;
}
因为新浪微博会将验证需要的code重定向到redirect_uri,而HttpClient貌似不支持,所以直接获取响应消息的code参数会报错。
我是通过获取响应的数据的Location值,即重定向地址来实现获取code的。这个Location的格式为redirect_uri?code=xxxxxxxx,我这里就是http://127.0.0.1?code=xxxxxxxx,通过截取Location来获取code,然后将code值传给SDK中提供的获取AccessToken的方法就可以成功获取到AccessToken了。