你可以这样做
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
public class Sandbox{
public static void main(String[] args) throws IOException {
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
System.out.println(credentials.getAccessToken());
}
}
有了这种依赖性
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
<version>1.1.0</version>
</dependency>
对于遇到此问题的其他人,@Nikhil VJ 的评论让我想到了这样有效的方法:
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.AccessToken;
import java.io.IOException;
public class Example {
private static void setup() throws IOException {
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
credentials.refreshIfExpired();
System.out.Println(credentials.getAccessToken().getTokenValue());
}
}
credentials.refreshIfExpired()
是我所缺少的。