繁体   English   中英

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

[英](JAVA) Google API analytics - unable to obtain new “access token” using “refresh token”

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

这是我写的代码:

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中被视为转义字符。

看起来您可能已经找到了一些过时的文档。 您链接的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();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM