java - Google 日历获取每个日历中的所有事件

标签 java google-api google-calendar-api google-api-java-client

我想检索日历中的所有事件,然后按日历对它们进行分类。

这是我到目前为止所拥有的。

public class Quickstart {
/** Application name. */
private static final String APPLICATION_NAME =
    "Google Calendar API Java Quickstart";

/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(
    System.getProperty("user.home"), ".credentials/calendar-java-quickstart");

/** Global instance of the {@link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;

/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY =
    JacksonFactory.getDefaultInstance();

/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;

/** Global instance of the scopes required by this quickstart.
 *
 * If modifying these scopes, delete your previously saved credentials
 * at ~/.credentials/calendar-java-quickstart
 */
private static final List<String> SCOPES =
    Arrays.asList(CalendarScopes.CALENDAR_READONLY);

static {
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
    // Load client secrets.
   BufferedReader br = new BufferedReader( new FileReader("C:\\Users\\User\\.credentials\\calendar-java-quickstart\\client_secret.json"));
   GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, br);

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(
                    HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(DATA_STORE_FACTORY)
            .setAccessType("offline")
            .build();
    Credential credential = new AuthorizationCodeInstalledApp(
        flow, new LocalServerReceiver()).authorize("user");
    System.out.println(
            "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    return credential;
}

/**
 * Build and return an authorized Calendar client service.
 * @return an authorized Calendar client service
 * @throws IOException
 */
public static com.google.api.services.calendar.Calendar
    getCalendarService() throws IOException {
    Credential credential = authorize();
    return new com.google.api.services.calendar.Calendar.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName(APPLICATION_NAME)
            .build();
}


public static void main(String[] args) throws IOException {
    // Build a new authorized API client service.
    // Note: Do not confuse this class with the
    //   com.google.api.services.calendar.model.Calendar class.
    com.google.api.services.calendar.Calendar service =
        getCalendarService();
    String pageToken = null;
    // List the next 10 events from the primary calendar.
    DateTime now = new DateTime(System.currentTimeMillis());
    Events events = service.events().list("primary")
        .setPageToken(pageToken)
        .setMaxResults(10)
        .setTimeMin(now)
        .setOrderBy("startTime")
        .setSingleEvents(true)
        .execute();
    List<Event> items = events.getItems();
    do 
    {
        CalendarList calendarList = service.calendarList().list().setPageToken(pageToken).execute();
        List<CalendarListEntry> items2 = calendarList.getItems();

        for (CalendarListEntry calendarListEntry : items2)
        {
             System.out.println(calendarListEntry.getSummary());
        }//for
          while(pageToken != null)
          pageToken = calendarList.getNextPageToken();
    }//do
    while (pageToken != null);
    System.out.println("------------------------------");
    if (items.size() == 0) 
    {
        System.out.println("No upcoming events found.");
    }//if
    else 
    {
        for (Event event : items) 
        {
            DateTime start = event.getStart().getDateTime();
            if (start == null) 
            {
                start = event.getStart().getDate();
            }//if
            System.out.println(event.getSummary());
        }//for
    }//else
}//main

如您所见,我可以获取所有事件(从主日历)以及所有可用日历的名称。

如何获取 calendarId 以便按日历对事件进行排序?

最佳答案

日历列表返回 clandarListResponse

{
  "kind": "calendar#calendarList",
  "etag": etag,
  "nextPageToken": string,
  "nextSyncToken": string,
  "items": [
    calendarList Resource
  ]
}

您已经在循环每个calendarListEntry,但您应该只请求您想要的字段(在本例中为id),而不是进行摘要。

每个calendar#calendarListEntry有一个 id 值,它是您要查找的日历 id。

我不是java开发人员,但我猜想是这样的

for (CalendarListEntry calendarListEntry : items) {
    System.out.println(calendarListEntry.getId());
 }

关于java - Google 日历获取每个日历中的所有事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42530571/

相关文章:

java - 具有可变字段的不可变对象(immutable对象)

java - JAVA Web 应用程序中基于表单的身份验证重试

iphone - iphone NSString 的问题

python - Youtube API 请求凭据

android - 我可以将 Google plus Sign In 添加为 android studio 中的模块吗?

regex - 是否可以在 CalendarApp.getEvents() 中使用带有搜索参数的正则表达式?

ios - 选择日历以添加 iOS 事件

java - X的辅助类在不同的java项目之间共享,每个项目使用不同版本的X

java - Android Studio模拟器: "Could not access the Package Manager." and "AdbCommandRejectedException: device ' emulator-555 6' not found"

ios - Google Calendar API 事件插入总是返回 404 “not found” 错误 iOS