【问题标题】:Unable to get access token with GoogleCredentials无法使用 GoogleCredentials 获取访问令牌
【发布时间】:2017-11-17 07:05:44
【问题描述】:

我正在尝试使用我的服务帐户 JSON 文件获取访问令牌。但是我无法获取访问令牌。

GoogleCredential googleCredential = GoogleCredential.fromStream(new FileInputStream(serviceAccountJsonFile));
System.out.print(googleCredential.getAccessToken());

我每次都收到null。 我可以在 Python API 中使用相同的凭据。

如果我在这里遗漏了什么,有人可以指出我。

【问题讨论】:

  • 我遇到了同样的问题,你成功了吗。
  • 是的。可以使用以下代码:GoogleCredential googleCredential = GoogleCredential.fromStream(new FileInputStream(serviceAccountJsonFile), GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance());
  • 我的 GoogleCredential 对象中没有 GetAccessToken() 方法。我的基于服务帐户。有什么想法吗?

标签: google-api google-oauth-java-client


【解决方案1】:

所以我自己解决了这个问题,在 getToken 之前添加了以下命令:

credential.refreshToken()

您的代码如下所示:

GoogleCredential googleCredential = GoogleCredential.fromStream(new FileInputStream(serviceAccountJsonFile));
credential.refreshToken();
System.out.print(googleCredential.getAccessToken());

这在 google 的网站中没有正确记录,但添加后,效果很好,结果显示为实际值。

我遇到的其他一些错误是“com.google.common.io.ByteStreams.exhaust(Ljava/io/InputStream;)J”,为了解决它,我必须更正我对这个的依赖:

<dependency>
 <groupId>com.google.api-client</groupId>
 <artifactId>google-api-client</artifactId>
 <version>1.31.1</version>
</dependency>

参考可以找到here

我希望这对你也有帮助!

【讨论】:

  • GoogleCredential 已折旧。您能否提供使用 GoogleCredentials 获取访问令牌的示例?现在末尾有一个“s”。
猜你喜欢
  • 2013-08-23
  • 2022-01-01
  • 2012-12-10
  • 1970-01-01
  • 2016-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多