调用日历 API 返回 403 状态,并显示使用限制超出消息



我正在尝试使用java从服务器创建事件。

这是我的代码。

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";
private static final List<String> SCOPES = Collections.singletonList(CalendarScopes.CALENDAR);
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
private static final String projfilepath = "/quickstart-foxmatrix.json";
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws Exception {
// 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(9000).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
public static void main(String... args) throws Exception {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
InputStream in = CalendarQuickstart.class.getResourceAsStream(projfilepath);
GoogleCredential credential = GoogleCredential.fromStream(in)
.createScoped(Collections.singleton(CalendarScopes.CALENDAR));
Calendar service = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
CalendarQuickstart obj = new CalendarQuickstart();
obj.createEvent(service);
}
public String createEvent(Calendar service) throws IOException {
Event event = new Event().setSummary("New Event")
.setDescription("A chance to hear more about Google's developer products.");
DateTime startDateTime = new DateTime("2020-02-04T09:00:00-07:00");
EventDateTime start = new EventDateTime().setDateTime(startDateTime);
event.setStart(start);
DateTime endDateTime = new DateTime("2020-02-04T17:00:00-07:00");
EventDateTime end = new EventDateTime().setDateTime(endDateTime);
event.setEnd(end);
EventAttendee[] attendees = new EventAttendee[] {
new EventAttendee().setEmail("hanil.kathuria@innovationm.com"),
new EventAttendee().setEmail("jijo.mathew@innovationm.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: %sn", event.getHtmlLink());
event.getHangoutLink();
return event.getHtmlLink();
}

我正在使用 JSON 文件中的服务帐户凭据。

我正在使用谷歌客户端库进行 api 调用。

我还检查了我的仪表板,api 调用的限制为 100/秒,并且没有显示 api 调用的 trafic。仍然当我尝试创建一个事件时,它显示超出了使用限制。

完全错误

线程"main"中的异常 com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 禁止 { "code" : 403, "errors" : [ { "domain" : "usageLimits", "message" : "Calendar Use Limits Overused.", "reason" : "quotaExceeded" } ], "message" : "Calendar Use Limits Beyond." }

您收到此错误是因为您尝试在不使用帐户模拟的情况下创建与与会者的活动,并且目前无法执行此操作,如此问题在Google问题跟踪器中看到的那样。

如果可能,您可以先与服务帐户共享日历,然后添加事件。但由于这是不可能的,所以你应该使用服务帐户来模拟自己:它应该代表你添加事件。

(重要说明:如果您使用不模拟的服务帐户并将calendarId设置为primary,就像您共享的代码中一样,则不会将事件添加到主日历,而是添加到服务帐户的主日历。服务帐号有自己的主日历、自己的云端硬盘等,与您的主日历、云端硬盘等不同

工作流程:

如果要使用服务帐户代表您访问资源,则必须执行以下操作:

  • 按照此处指定的步骤向服务帐号授予全网域授权。将服务帐户 ID 添加为Client Namehttps://www.googleapis.com/auth/calendar作为Manage API client access中的范围。
  • 下载与服务帐户对应的凭据(在下面提供的示例中,使用 P12 而不是 JSON(。
  • 使用服务帐户在生成凭据时指示你的电子邮件地址来模拟自己,如以下示例所示。

您可以通过以下方式构建凭据:

GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId("service-account@email-address") // Service account email
.setServiceAccountPrivateKeyFromP12File(new File("your-credentials.p12"))
.setServiceAccountScopes(Collections.singleton(CalendarScopes.CALENDAR))
.setServiceAccountUser("user@email-address") // Your email address (address of the user you want to impersonate)
.build();

参考:

  • 将网域范围的权限委派给服务帐号
  • 准备进行授权的 API 调用(服务帐户(
  • 类 GoogleCredential.Builder

我希望这有什么帮助。

您正在使用 Oauth2 的代码,而不是服务帐户 Google Analytics API 有一个非常好的 Java 服务帐户教程 快速入门服务帐户 java 不应该很难将其交换到日历上。

private static Calendar initializeCalendar() throws GeneralSecurityException, IOException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = GoogleCredential
.fromStream(new FileInputStream(KEY_FILE_LOCATION))
.createScoped(CalendarScopes.CALENDAR));
// Construct the Analytics service object.
return new Calendar.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
}

public static void main(String... args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
Calendar service = initializeCalendar();
// 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);
}
}

这应该很接近,但我现在没有 java 编译器的能力。

最新更新