(JAVA)Google API分析 - 无法使用“刷新令牌”获取新的“访问令牌”

时间:2012-11-06 18:34:21

标签: java access-token google-api-java-client

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

这是我写的代码:

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 Bad

     

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

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

我根据javadoc.google-oauth-java-client编写了代码。

此处的任何人都知道如何修改代码以获取新的访问令牌?

提前致谢。

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

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:1)

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