Java:Oauth 2.0如何使用Google API刷新量,以避免每次启动我的应用时请求访问?

StackOverflow https://stackoverflow.com/questions/8800466

Google API有很多示例代码显示如何获得授权令牌并使用它,但是我找不到任何示例代码向您展示如何使用OAuth 2.0 GoogleAccessprotectectedResource.refreshtoken()在Java客户端中以获取java Client Java的新授权令牌。 Google搜索一无所获,我只能在Stackoverflow上找到C#示例。如果您可以在Java中指出一些示例代码,以显示如何做到这一点。我在Android上工作的平台。我想使用的OAuth 2.0模型的一个示例: http://blog.doityourselfandroid.com/2011/08/06/oauth-2-0-flow-android/

非常感谢

有帮助吗?

解决方案

在这里回答我自己的问题。事实证明,它是很简单的,它通过致电GoogleAccessProtectedResource.refreshtoken()访问式访问式介绍,可以通过其Getter根据需要阅读和重复使用。

其他提示

您将不得不捕获401(未经授权)错误。之后做这样的事情。

accountManager.invalidateAuthToken(accessProtectedResource.getAccessToken());
accessProtectedResource.setAccessToken(null);

之后,只需恢复令牌即可。这次用户将不必再次授权访问。

        accountManager.manager.getAuthToken(account, AUTH_TOKEN_TYPE, true,
        new AccountManagerCallback<Bundle>() {
          @Override
          public void run(AccountManagerFuture<Bundle> future) {
            try {
              Bundle bundle = future.getResult();
              if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
                intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivityForResult(intent, REQUEST_AUTHENTICATE);
              } else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                accessProtectedResource.setAccessToken(bundle.getString(AccountManager.KEY_AUTHTOKEN));
                onAuthToken();
              }
            } catch (Exception e) {
              handleException(e);
            }
          }
        }, null);

参考 任务样本 参考和相应的 文章.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top