如何在Java中集成Google日历客户端和GoogleCredentials

5kgi1eie  于 2023-02-14  发布在  Java
关注(0)|答案(1)|浏览(128)

你好,我正在尝试使用谷歌日历客户端与谷歌凭据,但无法找到任何关于如何使这一工作的文档。请添加一个文档或让我知道如何使它工作。

package com.example;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import java.io.File;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import com.google.api.services.calendar.Calendar;
import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;

public class Main {

    public static void main(String[] args) throws GeneralSecurityException, IOException {
        // write your code here
        System.out.println("Hello");

        GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("target/classes/credentials.json"));
        AccessToken token = credentials.getAccessToken();

        Calendar client = new Calendar.Builder((HttpTransport) GoogleNetHttpTransport.newTrustedTransport(), (JsonFactory) new GsonFactory(), (HttpRequestInitializer) credentials).build();
        System.out.println(client.calendarList().list().execute());
    }
}

我试过使用GoogleCredential,但现在已经过时了,所以我不得不切换到GoogleCredential。前两行在我获得访问令牌之前一直有效。我正在创建日历客户端的行导致编译时错误。

Exception in thread "main" java.lang.ClassCastException: class com.google.auth.oauth2.ServiceAccountCredentials cannot be cast to class com.google.api.client.http.HttpRequestInitializer (com.google.auth.oauth2.ServiceAccountCredentials and com.google.api.client.http.HttpRequestInitializer are in unnamed module of loader 'app')
    at com.example.Main.main(Main.java:29)
htrmnn0y

htrmnn0y1#

我觉得你是在效仿一个老例子

private static Calendar initializeAnalyticsReporting() throws GeneralSecurityException, IOException {

    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential
        .fromStream(new FileInputStream(KEY_FILE_LOCATION))
        .createScoped(CalendarScopes.all());

    // Construct the Calendar service object.
    return new Calendar.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();
  }

相关问题