作了幾個新浪分享的項目,昨天遇到了獲取不到accessToken,而是受權成功只返回個code,這讓我比較糾結,看了新浪官方說須要用code值算accessToken,又看了官方的demo,裏面寫個暫時不提供code算法,讓我很鬱悶,又搜了下新浪提供了接口能夠經過code取accessToken,先把代碼粘上:(多餘的就不粘了,只貼關鍵部分)android
/** 新浪微博受權成功回調方法 */算法
class AuthDialogListener implements WeiboAuthListener {json
@Override public void onComplete(Bundle values) { final String code = values.getString("code"); token = values.getString("access_token"); expires_in = values.getString("expires_in"); if(TommyTools.isNull(token)){ accessToken = new Oauth2AccessToken(token, expires_in); if (accessToken.isSessionValid()) { AccessTokenKeeper.keepAccessToken(activity, accessToken); Toast.makeText(activity, "認證成功", Toast.LENGTH_SHORT).show(); } }else if (code != null) {//下面是經過code取accessToken new Thread(){ @Override public void run() { String result = ""; WeiboParameters params = new WeiboParameters(); params.add("client_id", Constant.APP_KEY); params.add("client_secret", "1f39c10940fa0d3b1001e439c4a99ccb"); params.add("grant_type", "authorization_code"); params.add("redirect_uri", Constant.REDIRECT_URL); params.add("code", code); try { result = HttpManager.openUrl("https://api.weibo.com/oauth2/access_token", "POST", params, null); } catch (WeiboException e) { e.printStackTrace(); } JSONObject json; try { json = new JSONObject(result); token = json.getString("access_token"); expires_in = json.getString("expires_in"); handler.sendEmptyMessage(1); } catch (JSONException e) { e.printStackTrace(); } } }.start(); }else{ return; } } @Override public void onError(WeiboDialogError e) { Toast.makeText(activity, "Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show(); } @Override public void onCancel() { Toast.makeText(activity, "Auth cancel", Toast.LENGTH_LONG).show(); } @Override public void onWeiboException(WeiboException arg0) { } }
Handler handler = new Handler(){api
@Override public void handleMessage(Message msg) { if(msg.what == 1){ if(TommyTools.isNull(token) && TommyTools.isNull(expires_in)){ accessToken = new Oauth2AccessToken(token, expires_in); if (accessToken.isSessionValid()) { AccessTokenKeeper.keepAccessToken(activity, accessToken); Toast.makeText(activity, "認證成功", Toast.LENGTH_SHORT).show(); } } } } };
能夠看到,我在受權成功回調那裏作了個判斷,先判斷token爲不爲空,直接說緣由,是由於在申請appKey時android須要填寫包名和應用簽名,若是打的包用的簽名和填寫在上面的一致,受權成功會直接返回token,不須要在調接口獲取,若是簽名不一致,受權就只返回一個code碼,而後經過code碼再獲取token。app