0
代碼在JavaEE服務器(Wildfly)上運行,並在Linux OS(不帶GUI的Raspbian)上運行。我想在後臺進程中訪問Gmail API,但他總是問我「請在瀏覽器中打開以下地址:....」。我能以某種方式防止這種情況嗎以編程方式在後臺Java進程中訪問Google API授權
InputStream in = XmlServiceImpl.class
.getResourceAsStream("/mail.connector/client_secret.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline").setApprovalPrompt("force").build();
Credential credential = new AuthorizationCodeInstalledApp(flow,
new LocalServerReceiver()).authorize("user");
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
Credential credential = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
Gmail service = null;
try {
service = getGmailService();
} catch (IOException e1) {
// TODO Exception Handling
e1.printStackTrace();
}
ListMessagesResponse response = null;
try {
response = service.users().messages().list(USER_ID)
.setIncludeSpamTrash(true).execute();
} catch (IOException e) {
// TODO Exception Handling
e.printStackTrace();
}
授權必須通過瀏覽器至少進行一次。對於以後的登錄,您可以存儲令牌/憑證並在需要時訪問它們。你的情況很新穎,但我認爲如果你使用服務帳戶會更好。 –
但是,我可以通過服務帳戶訪問Gmail郵件嗎?我沒有收到「Google for Works」帳戶。 –
我懷疑您是否可以通過服務帳戶訪問Gmail。您可以使用Google雲端硬盤,因爲您可以與服務帳戶共享文件夾和文檔。 –