试试这些代码片段:
片段1:
public void authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
List <String> scopes = new LinkedList<String>();
scopes.add(scope);
AuthorizationCodeRequestUrl authorize = new GoogleAuthorizationCodeRequestUrl(client_id, redirect_uri, scopes);
authorize.setRedirectUri(redirect_uri);
String authorize_url = authorize.build();
log.info(authorize_url);
response.sendRedirect(authorize_url);
}
片段一负责 OAuth 并将程序重定向到重定向 uri。变量 scope、client_id、cliend_secret 和 scope 的值来自 Google api 控制台。
片段 2:
public void importCalendarList(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String code = request.getParameter("code");
HttpTransport transport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleTokenResponse res = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, client_id, client_secret, code, redirect_uri).execute();
]String accessToken = res.getAccessToken();
Calendar.Builder builder = new Calendar.Builder(transport, jsonFactory, null);
builder.setCalendarRequestInitializer(new CalendarRequestInitializer(accessToken));
Calendar calendarService = builder.build();
Calendar.CalendarList.List list = calendarService.calendarList().list();
list.setOauthToken(accessToken);
List <CalendarListEntry>list1=list.execute().getItems();
String id = list1.get(0).getId();
p.write(id);
for(CalendarListEntry temp:list1) {
p.println(temp.getSummary());
temp.getId();
}
Event e = new Event();
e.setSummary("Test event");
e.setLocation("Adaptavant");
Date startDate = new Date();
Date endDate = new Date(startDate.getTime() + 3600000);
DateTime start = new DateTime(startDate, TimeZone.getTimeZone("UTC"));
e.setStart(new EventDateTime().setDateTime(start));
DateTime end = new DateTime(endDate, TimeZone.getTimeZone("UTC"));
e.setEnd(new EventDateTime().setDateTime(end));
Event insertedEvent = calendarService.events().insert(id, e).setOauthToken(accessToken).execute();
p.println(insertedEvent.getId());
}
片段二获取日历列表并获取其中一个的 id 并在该日历中创建一个事件。如果要将事件添加到主日历,则主日历的 id 是用于登录的 gmail id。
更多文档可在此处找到:
https://google-api-client-libraries.appspot.com/documentation/calendar/v3/java/latest/index.html