我尝试使用带有服务帐户凭据和Java SDK(v1.22.0)的Gmail API访问我自己的个人Gmail帐户。我已经生成了凭据并在本地保存了json文件,然后尝试运行它:
公共类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)
我已尝试在服务凭据上启用域范围授权,并且我已尝试更改用户&#34; me&#34;到我帐户的电子邮件地址,但结果相同。我也看过一些有类似问题的问题,但我发现其中任何一个问题都没用。我错过了什么吗?
Gmail API已从开发者控制台启用,从那里我可以看到所有失败的4xx请求。
我还应该提到我已经使用Python创建了另一个测试,它使用相同的服务凭据执行完全相同的操作,并且失败时出现相同的400错误。我尝试在相同的安全凭证下创建一个新密钥(json)并尝试使用它,但它的结果相同。
我已经能够让事情有效,但只能使用替代的oAuth登录过程,即提示允许/拒绝来自网络浏览器的访问,然后将一些oAuth访问权限保存到未来用户的文件。这并不理想,因为我将不得不不断更新这些令牌。大概是为了避免这个确切的问题而创建服务凭证。我仍然非常有兴趣了解它为什么不适合我。
答案 0 :(得分:2)
服务帐户域范围授权仅适用于G Suite帐户,并要求G Suite管理员授权服务帐户客户端ID访问必要的范围。如果您正在使用消费者Gmail帐户(@ gmail.com地址),或者您没有获得G Suite管理员批准,那么您应该像使用现在一样使用正常的OAuth流程。