我用下面的代码用Java API(使用一个服务帐户)构建一个Google日历服务:
/**
* Return a google Calendar object for interacting with the calendar API.
* Return null if it can't be built for any reason
*/
private Calendar buildGoogleCalendarService() throws GeneralSecurityException, IOException {
String googleUsername = this.getGoogleUsername();
if (googleUsername == null) {
return null;
}
String path = AuthManager.class.getClassLoader().getResource("").getPath();
File privateKey = new File(path + "/google_key.p12");
if (!privateKey.exists()) {
logger.error("Google private key not found at " + privateKey.getAbsolutePath());
return null;
}
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jsonFactory).setServiceAccountId(AppProperties.googleAppEmailAddress)
.setServiceAccountPrivateKeyFromP12File(privateKey)
.setServiceAccountScopes(Collections.singleton(CalendarScopes.CALENDAR))
.setServiceAccountUser(googleUsername).build();
Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credential)
.setApplicationName(AppProperties.appName).build();
return service;
}
它在一些基本测试中工作得很好,问题是凭证/服务能够被重用多长时间?即,在重新生成之前,您可以使用它发出多少API请求?此服务器应用程序可能处理大量API调用,并且在重新启动之间持续几个月。
做一些计时,凭证构建阶段(GoogleCredential credential = new GoogleCredential. builder()…)花费的时间最多,大约。等一下,我先缓存一下看看效果如何,欢迎大家踊跃回答
由于您没有直接指定访问令牌,因此GoogleCredential
将自动刷新令牌。您似乎已经遵循了OAuth 2文档,因此不需要更多的内容。