当我尝试使用服务帐户访问 Google Cloud Storage API 时收到 invalid_grant 错误。我无法弄清楚以下代码有什么问题。任何的想法 ?这是我第一个使用 Google Storage API 的应用程序。任何帮助将不胜感激。
源代码
public static void main(String[] args) throws Exception {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
List<String> scopes = new ArrayList<String>();
scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
Credential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("XXXX")
.setServiceAccountPrivateKeyFromP12File(new File("key.p12"))
.setServiceAccountScopes(scopes).build();
Storage storage = new Storage.Builder(httpTransport, jsonFactory,
credential).setApplicationName("test")
.build();
List<String> list = new ArrayList<String>();
List<Bucket> buckets = storage.buckets().list("XXXX").execute().getItems();
if(buckets != null) {
for(Bucket b : buckets) {
list.add(b.getName());
}
}
}
错误和堆栈跟踪
Exception in thread "main" com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "invalid_grant"
}
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:269)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:858)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
at GoogleStorageFetcher.main(GoogleStorageFetcher.java:143)