我试图使用具有服务帐户凭据和Java SDK(v1.22.0)的Gmail API访问我自己的个人Gmail帐户。我已经生成的证书和本地保存JSON文件,然后试图运行以下命令:使用Java SDK返回400的Google Gmail API请求
公共类GmailAPITest {
public static void main(String[] args) throws Exception {
JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
HttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
String filepath = "/path/to/my/creds.json";
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(filepath))
.createScoped(Collections.singleton(GmailScopes.GMAIL_READONLY));
Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName("MyApp")
.build();
String user = "me";
ListLabelsResponse listResponse = service.users().labels().list(user).execute();
List<Label> labels = listResponse.getLabels();
if (labels.size() == 0) {
System.out.println("No labels found.");
} else {
System.out.println("Labels:");
for (Label label : labels) {
System.out.printf("- %s\n", label.getName());
}
}
}
我得到一个400回应是这样的:
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Bad Request",
"reason" : "failedPrecondition"
} ],
"message" : "Bad Request"
}
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
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:1065)
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)
at ie.test.GmailAPITest.main(GmailAPITest.java:34)
我已经尝试启用服务凭据的域范围委派,并且我已尝试将用户“我”更改为我的帐户的电子邮件地址,但这是相同的结果。我也看到了许多类似问题的问题,但我没有发现它们有用。我错过了什么吗?
Gmail API已在开发者控制台中启用,从那里我可以看到所有失败的4xx请求。
我还应该提到,我已经使用Python创建了另一个测试,它使用相同的服务凭证执行完全相同的操作,并且它以相同的400错误失败。我试着在同一个安全证书下创建一个新的密钥(json)并尝试使用它,但它是相同的结果。
我已经能够得到的东西的工作,但只能通过使用可替代的OAuth登录过程中即被提示允许/拒绝从网络浏览器,然后保存一些OAuth访问令牌访问未来用户的文件。这并不理想,因为我将不得不不断更新这些令牌。服务凭据大概是为了避免确切的问题而创建的。我仍然很想知道为什么它不适合我。