5

我想根据数据库中保存的“刷新令牌”获取新的“访问令牌”。

这是我写的代码:

GoogleCredential.Builder credentialBuilder = new GoogleCredential.Builder()
        .setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
        .setClientSecrets(CLIENT_ID, CLIENT_SECRET);
credentialBuilder.addRefreshListener(new MyCredentialRefreshListener());

credential = credentialBuilder.build();
credential.setRefreshToken("saved_refresh_token_from_database");

try {
    credential.refreshToken();
} catch (IOException e) {
    e.printStackTrace();
}


class MyCredentialRefreshListener implements CredentialRefreshListener {
    public void onTokenResponse(Credential cr, TokenResponse tr) {
       System.out.println("Credential was refreshed successfully.");
    }

    public void onTokenErrorResponse(Credential cr, TokenErrorResponse tr) {
        System.out.println(tr);
    }
 }

我收到这条消息:

com.google.api.client.auth.oauth2.TokenResponseException: 400 错误

请求{“错误”:“invalid_grant”}

我在 php 脚本中使用相同的 CLIENT_ID、CLIENT_SECRET 和“刷新令牌”,当“访问令牌”过期时,我设法使用“刷新令牌”获取新的“访问令牌”。

我基于javadoc.google-oauth-java-client编写了代码。

这里的任何人都知道如何修改代码以获得新的访问令牌?

提前致谢。

更新:问题是我在数据库中保存了 refresh_token 而没有对其进行 json_decode 并且它包含一个“\”,它被认为是 JSON 中的转义字符。

4

2 回答 2

2

看起来您可能发现了一些过时的文档。您链接的 JavaDoc 适用于客户端库的 1.8 版。当前版本是 1.12。

客户端库作者建议您使用它GoogleAuthorizationCodeFlow来管理 OAuth 凭据。它会自动处理刷新。如果您遵循此路径,代码将如下所示:

// Create the flow 
AuthorizationCodeFlow authorizationCodeFlow = new GoogleAuthorizationCodeFlow.Builder(
    new UrlFetchTransport(), new JacksonFactory(), CLIENT_ID, CLIENT_SECRET,
    Collections.singleton(OAUTH_SCOPES))
    .setAccessType("offline")
    .setCredentialStore(new AppEngineCredentialStore())
    .build();

// User Id: e.g. from session 
Credential credential = authorizationCodeFlow.loadCredential(USER_ID);     

// Make your API call. This example uses the Google+ API
// If the access token has expired, it will automatically refresh
Plus plus = new Plus(new UrlFetchTransport(), new JacksonFactory(), credential)
  .activities().list("me", "public").execute();
于 2012-11-26T20:13:04.720 回答
1

如果你得到 http 状态 400,并且消息“invalid_grant”。我认为您应该检查您的HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET 实例

于 2013-09-10T02:04:19.343 回答