首页 > 解决方案 > Java 和 Google API:连接到谷歌邮件并在我的谷歌日历中添加事件?

问题描述

我在 Java 中使用 JavaFX 进行编程,如果我们可以这样称呼它,我会在我的 excel 中发送我的“对象”,但我希望朋友们将它发送到我的谷歌日历上。要连接,我想把我的地址和密码都输入硬,因为只有我会使用这个程序。只是,我已经阅读并重新阅读了 google api 文档(我明白其中的一半显然我必须连接到 Oauth,然后将数据发送到日历,顺便说一下,我有访问密钥)但我几乎一无所知从未使用过 API。

总结:我想连接到我的谷歌电子邮件地址并将事件发送到我的谷歌日历:

该事件进入我的日历“日历 AWBB”

在我的 excel 中,一个示例结果是:

谢谢大家:)

这是我需要此代码的函数:

@FXML
protected void EnvoiDonneesChampionnat()
{
    /*Call service*/
    SvcResultat Create = new SvcResultat();
    /*data correct ?*/
    if(datePickerDateMatch.getValue()==null || choiceBoxAdresse.getValue()==null || choiceBoxMin.getValue()==null || choiceBoxCategorie.getValue()==null ||
    choiceBoxEquipeA.getValue()==null || choiceBoxEquipeB.getValue()==null || choiceBoxHeure.getValue()==null){
        erreur.setText("Data is missing");
    }
    else {
        /*Create objet*/
        String result = datePickerDateMatch.getValue().toString()+";"+choiceBoxHeure.getValue().toString()+":"
                +choiceBoxMin.getValue().toString()+";Championnat;"+choiceBoxCategorie.getValue().toString()+";Programm\\u00e9;"
                +choiceBoxEquipeA.getValue().toString()+";;;"+choiceBoxEquipeB.getValue().toString()+";"
                +choiceBoxCategorie.getValue().toString()+";"+choiceBoxAdresse.getValue().toString()+";"
                +textFieldCollegue.getText()+";"+textFieldNotes.getText();
        System.out.println(result);
        /*Object go in my excel*/
        Create.ajoutResultat(result);

    }
 // method for create a google calendar event
}

标签: javagoogle-apigoogle-calendar-api

解决方案


日历 API文档中,有关于如何将 API 与 java 一起使用的指南。

您可以使用其中两个指南/示例。第一个是关于 Java 的快速入门指南,它将向您展示如何执行 API。

另一个是Create Events指南,其中有一个使用 Java 创建事件的示例。

将两者结合起来,您将通过 API 为您的帐户创建一个事件

这是两者的代码:

快速开始:

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Events;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class CalendarQuickstart {
    private static final String APPLICATION_NAME = "Google Calendar API Java Quickstart";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String TOKENS_DIRECTORY_PATH = "tokens";

    /**
     * Global instance of the scopes required by this quickstart.
     * If modifying these scopes, delete your previously saved tokens/ folder.
     */
    private static final List<String> SCOPES = Collections.singletonList(CalendarScopes.CALENDAR_READONLY);
    private static final String CREDENTIALS_FILE_PATH = "/credentials.json";

    /**
     * Creates an authorized Credential object.
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws IOException If the credentials.json file cannot be found.
     */
    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        // Load client secrets.
        InputStream in = CalendarQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (in == null) {
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        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(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("offline")
                .build();
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
        return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
    }

    public static void main(String... args) throws IOException, GeneralSecurityException {
        // Build a new authorized API client service.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Calendar service = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();

        // List the next 10 events from the primary calendar.
        DateTime now = new DateTime(System.currentTimeMillis());
        Events events = service.events().list("primary")
                .setMaxResults(10)
                .setTimeMin(now)
                .setOrderBy("startTime")
                .setSingleEvents(true)
                .execute();
        List<Event> items = events.getItems();
        if (items.isEmpty()) {
            System.out.println("No upcoming events found.");
        } else {
            System.out.println("Upcoming events");
            for (Event event : items) {
                DateTime start = event.getStart().getDateTime();
                if (start == null) {
                    start = event.getStart().getDate();
                }
                System.out.printf("%s (%s)\n", event.getSummary(), start);
            }
        }
    }
}

创建事件:

// Refer to the Java quickstart on how to setup the environment:
// https://developers.google.com/calendar/quickstart/java
// Change the scope to CalendarScopes.CALENDAR and delete any stored
// credentials.

Event event = new Event()
    .setSummary("Google I/O 2015")
    .setLocation("800 Howard St., San Francisco, CA 94103")
    .setDescription("A chance to hear more about Google's developer products.");

DateTime startDateTime = new DateTime("2015-05-28T09:00:00-07:00");
EventDateTime start = new EventDateTime()
    .setDateTime(startDateTime)
    .setTimeZone("America/Los_Angeles");
event.setStart(start);

DateTime endDateTime = new DateTime("2015-05-28T17:00:00-07:00");
EventDateTime end = new EventDateTime()
    .setDateTime(endDateTime)
    .setTimeZone("America/Los_Angeles");
event.setEnd(end);

String[] recurrence = new String[] {"RRULE:FREQ=DAILY;COUNT=2"};
event.setRecurrence(Arrays.asList(recurrence));

EventAttendee[] attendees = new EventAttendee[] {
    new EventAttendee().setEmail("lpage@example.com"),
    new EventAttendee().setEmail("sbrin@example.com"),
};
event.setAttendees(Arrays.asList(attendees));

EventReminder[] reminderOverrides = new EventReminder[] {
    new EventReminder().setMethod("email").setMinutes(24 * 60),
    new EventReminder().setMethod("popup").setMinutes(10),
};
Event.Reminders reminders = new Event.Reminders()
    .setUseDefault(false)
    .setOverrides(Arrays.asList(reminderOverrides));
event.setReminders(reminders);

String calendarId = "primary";
event = service.events().insert(calendarId, event).execute();
System.out.printf("Event created: %s\n", event.getHtmlLink());

推荐阅读