我确实设置了服务帐户并下载了用于创建凭证的JSON文件,如下所示:
https://developers.google.com/identity/protocols/OAuth2ServiceAccount#callinganapi
如果使用JSON文件创建凭证,则以下代码会引发错误:
GoogleCredential credential1 = GoogleCredential.fromStream(new FileInputStream("Project-1234.json"))
.createScoped(Collections.singleton(GMAIL_SCOPE));
相反,如果我使用P12文件创建凭证,它可以正常工作:
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(serviceAccountUserEmail)
.setServiceAccountPrivateKeyFromP12File(new File("Project-123.p12"))
.setServiceAccountScopes(Collections.singleton(GMAIL_SCOPE))
.setServiceAccountUser("sdkg1308@gmail.com")
.build();
这是使用JSON文件创建凭据对象时出现的错误:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Bad Request",
"reason" : "failedPrecondition"
} ],
"message" : "Bad Request"
}
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1056)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
如果google API不支持JSON格式,那么为什么在文档中提到它是为服务帐户存储生成的密钥的推荐方法。