新浪微博开发之自动获取AccessToken

第一篇博客。

前段时间研究新浪微博开发,发现官方提供的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了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值