【发布时间】:2021-07-08 08:52:21
【问题描述】:
我创建了一个服务帐户来进行日历 api 调用;但是当我的代码运行时,一切看起来都很完美。但是返回的数据是空的。我在谷歌网页上提供的api调试功能,调用的时候可以返回数据。链接 => https://developers.google.com/calendar/v3/reference/calendarList/list#examples
我的java代码
package org.test.google;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
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.services.calendar.Calendar;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.CalendarList;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
public class CalendarTest {
private static final Set<String> scopes = Arrays.stream(new String[]{
CalendarScopes.CALENDAR,
CalendarScopes.CALENDAR_EVENTS,
CalendarScopes.CALENDAR_EVENTS_READONLY,
CalendarScopes.CALENDAR_READONLY,
CalendarScopes.CALENDAR_SETTINGS_READONLY,
}).collect(Collectors.toSet());
public static void main(String[] args) throws GeneralSecurityException, IOException {
NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
Credential credential = getCredential(httpTransport, jsonFactory);
Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credential).setApplicationName("space").build();
CalendarList calendarList = service.calendarList().list().execute();
System.out.println(calendarList);
if (calendarList.getItems().size() == 0) {
System.out.println("no data");
}
}
private static GoogleCredential getCredential(HttpTransport httpTransport, JsonFactory jsonFactory) throws IOException {
return GoogleCredential.fromStream(
new FileInputStream("/Users/clk528/Download/google/json/space-0c23309aa763.json"),
httpTransport,
jsonFactory
).createScoped(scopes);
}
}
【问题讨论】:
-
此服务帐户是否有权访问日历,或者您是否在使用模拟?在日历 API 上试试这个,您以自己的身份发出请求,而不是以服务帐户的身份提出请求
标签: java google-api google-calendar-api google-api-java-client service-accounts