我正在尝试使用 GMAIL API 使用 OAuth 2.0 服务器从我的电子邮件帐户下载附件到服务器应用程序。这是我的代码:
private static final String USER = "MYACCOUNT@gmail.com";
private static String emailAddress = "XXXXXXXX@developer.gserviceaccount.com";
{
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(emailAddress)
.setServiceAccountPrivateKeyFromP12File(new File("myfile.p12"))
.setServiceAccountScopes(Collections.singleton(GmailScopes.GMAIL_READONLY))
.build();
}
catch (IOException | GeneralSecurityException e)
{
throw new RuntimeException(e);
}
}
// Create a new authorized Gmail API client
Gmail service = new Gmail.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APP_NAME).build();
// Retrieve a page of Threads
ListThreadsResponse threadsResponse = service.users().threads().list(USER).execute();
List<Thread> threads = threadsResponse.getThreads();
// Print ID of each Thread.
for (Thread thread : threads) {
System.out.println("Thread ID: " + thread.getId());
}
我在线程响应调用中收到错误。这些是错误:
线程"main"中的异常 com.google.api.client.googleapis.json.GoogleJsonResponseException: 500 内部服务器错误。
{ "代码" : 500, "错误" : [ { "域" : "全局", "消息" : "后端错误", "原因" : "后端错误" } ], "消息" : "后端错误"} 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:312) at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1049) 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 core.crescent.gmail.GmailApiQuickstart.main(GmailApiQuickstart.java:192)
您可以重试请求,但会使用指数退避。为我工作。见 https://developers.google.com/drive/web/handle-errors
所以我找出了问题并修复了它!
设置"凭据"时(在我上面发布的代码中)。我需要添加 .setServiceAccountUser(USER) 子例程。通过执行此操作,您可以在创建的服务帐户和要访问的GMAIL帐户之间建立链接。我在 https://developers.google.com/accounts/docs/OAuth2ServiceAccount 早些时候看到过它,但我的印象是,只有当您想与不同域名下的帐户链接时,才会看到它。
这解决了我的问题。谢谢大家的回复