Android Google Play 服务为 blogger api 返回无效 token

标签 android google-play-services token blogger

我已经获得了访问博客 API 的权限,我已经在我的开发者控制台上确认了这一点。 我还编写了一些代码,使用下面的一些代码通过 Google Play 服务执行 oAuth2。

String SCOPE ="oauth2:https://www.googleapis.com/auth/blogger";
GoogleAuthUtil.getToken(context, "myEmail@gmail.com", mScope);

它返回一个标记。正如它应该。 但是,一旦我尝试使用 token 访问 api,我就会收到错误消息。

Unexpected response code 403 for https://www.googleapis.com/blogger/v3/users/self/blogs

这是我的要求: enter image description here

这是我的回应:

enter image description here

这是我获取 token 的 BaseActivity.java 代码:

public class BaseActivity extends Activity {

static final int REQUEST_CODE_PICK_ACCOUNT = 1000;
static final int REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR = 1001;
static final int REQUEST_CODE_RECOVER_FROM_AUTH_ERROR = 1002;
private static final String SCOPE ="oauth2:https://www.googleapis.com/auth/blogger";
private String mEmail; // Received from newChooseAccountIntent(); passed to getToken()
public ProgressDialog mDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mDialog = new ProgressDialog(this);
    login();
}

public void login() {
    pickUserAccount();
}

private void pickUserAccount() {
    String[] accountTypes = new String[]{"com.google"};
    Intent intent = AccountPicker.newChooseAccountIntent(null, null, accountTypes, false, null, null, null, null);
    startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
        // Receiving a result from the AccountPicker
        if (resultCode == RESULT_OK) {
            mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);

            // With the account name acquired, go get the auth token
            getToken();
        } else if (resultCode == RESULT_CANCELED) {
            // The account picker dialog closed without selecting an account.
            // Notify users that they must pick an account to proceed.
            Toast.makeText(this, "Pick Account", Toast.LENGTH_SHORT).show();
        }
    } else if ((requestCode == REQUEST_CODE_RECOVER_FROM_AUTH_ERROR ||
            requestCode == REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR)
            && resultCode == RESULT_OK) {
        // Receiving a result that follows a GoogleAuthException, try auth again
        getToken();
    }
}

private void getToken() {
    if (mEmail == null) {
        pickUserAccount();
    } else {
        if (isDeviceOnline()) {
            new getTokenTask(BaseActivity.this, mEmail, SCOPE).execute();
        } else {
            Toast.makeText(this, "Not online", Toast.LENGTH_LONG).show();
        }
    }
}

/**
 * This method is a hook for background threads and async tasks that need to
 * provide the user a response UI when an exception occurs.
 */
public void handleException(final Exception e) {
    // Because this call comes from the AsyncTask, we must ensure that the following
    // code instead executes on the UI thread.
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (e instanceof GooglePlayServicesAvailabilityException) {
                // The Google Play services APK is old, disabled, or not present.
                // Show a dialog created by Google Play services that allows
                // the user to update the APK
                int statusCode = ((GooglePlayServicesAvailabilityException)e).getConnectionStatusCode();
                Dialog dialog = GooglePlayServicesUtil.getErrorDialog(statusCode, BaseActivity.this, REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
                dialog.show();
            } else if (e instanceof UserRecoverableAuthException) {
                // Unable to authenticate, such as when the user has not yet granted
                // the app access to the account, but the user can fix this.
                // Forward the user to an activity in Google Play services.
                Intent intent = ((UserRecoverableAuthException)e).getIntent();
                startActivityForResult(intent,  REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
            }
        }
    });
}

public boolean isDeviceOnline() {
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    } else {
        return false;
    }
}

public class getTokenTask extends AsyncTask{
    Activity mActivity;
    String mScope;
    String mEmail;

    getTokenTask(Activity activity, String name, String scope) {
        this.mActivity = activity;
        this.mScope = scope;
        this.mEmail = name;
    }

    @Override
    protected Object doInBackground(Object[] params) {
        try {
            String token = fetchToken();
            Preferences.saveString(Constants.KEY_BLOGGER_TOKEN, token);
        } catch (IOException e) {
            // The fetchToken() method handles Google-specific exceptions,
            // so this indicates something went wrong at a higher level.
            // TIP: Check for network connectivity before starting the AsyncTask.
        }
        return null;
    }


    /**
     * Gets an authentication token from Google and handles any
     * GoogleAuthException that may occur.
     */
    protected String fetchToken() throws IOException {
        try {
            return GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
        } catch (UserRecoverableAuthException userRecoverableException) {
            // GooglePlayServices.apk is either old, disabled, or not present
            // so we need to show the user some UI in the activity to recover.
            ((BaseActivity)mActivity).handleException(userRecoverableException);

        } catch (GoogleAuthException fatalException) {
            // Some other type of unrecoverable exception has occurred.
            // Report and log the error as appropriate for your app.
        }
        return null;
    }
}

在这个问题上,我一直在用头撞墙。有人有什么想法吗?

最佳答案

终于明白了。

我的 build.gradle 文件以某种方式最终具有与我的 list 不同的应用程序 ID。我改变了它,使它们都与 list 相匹配,然后繁荣!它奏效了。

关于Android Google Play 服务为 blogger api 返回无效 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27193434/

相关文章:

java - 从文本文件中提取 token ?

angularjs - 了解 Nodejs 和 Angular 中的密码重置

java - LibGDX 在暂停时停止时间计数器

编辑文本问题中的Android MVVM数据绑定(bind)设置错误

android - "public void onDestroy()"和 "protected void onDestroy()"之间的区别?

java - 应用未正确配置为使用 Google Play 游戏服务

android - 在 android 项目中使用 google Place picker

java - MediaStore 音频列数据已弃用

android - 为什么 FusedLoactionProvider.getLocationAvailability() 返回 null(虽然它不应该)?

gradle - 没有@@的任何字符串的Gradle replaceToken