以编程方式在后台Java进程中访问Google API授权

时间:2016-06-07 05:06:17

标签: java api gmail authorization access

代码在JavaEE Server(Wildfly)上运行,并在Linux OS(没有GUI的Raspbian)上运行。我想在后台进程中访问Gmail 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();
}

1 个答案:

答案 0 :(得分:0)

我使用JavaMailAPI从我的GMail帐户中读取邮件。见Link

完美无缺。