您好,我正在尝试将 Google 日历客户端与 GoogleCredentials 一起使用,但找不到任何有关如何实现此功能的文档。请添加文档或让我知道如何使其工作。
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,但它现在已经贬值,所以我不得不切换到 GoogleCredentials。前两行一直有效,直到我获得访问令牌。我创建日历客户端的行导致编译时错误。
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)
我认为你遵循了一个古老的例子
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();
}
以这种方式构建客户端,使用
HttpCredentialsAdapter
:
Calendar service = new Calendar.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
GsonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credentials))
.build();