我有一个服务帐户,该帐户设置了对Gsuite域的全域授权。我想假扮其中一位用户作为创建活动的组织者。
我的代码是:
List<String> scopes = new ArrayList<>();
scopes.add(CalendarScopes.CALENDAR);
scopes.add(CalendarScopes.CALENDAR_EVENTS);
InputStream credentialsJSON = Service5.class.getClassLoader()
.getResourceAsStream("credentials.json");
GoogleCredential gcFromJson = GoogleCredential.fromStream(credentialsJSON, HTTP_TRANSPORT, JSON_FACTORY).createScoped(scopes);
GoogleCredential cred = new GoogleCredential.Builder()
.setTransport(gcFromJson.getTransport())
.setJsonFactory(gcFromJson.getJsonFactory())
.setServiceAccountId(gcFromJson.getServiceAccountId())
.setServiceAccountUser("[email protected]")
.setServiceAccountPrivateKey(gcFromJson.getServiceAccountPrivateKey())
.setServiceAccountScopes(gcFromJson.getServiceAccountScopes())
.build();
Calendar service = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, cred).setApplicationName(APPLICATION_NAME).build();
Event event = new Event().setSummary("Test");
DateTime startDateTime = new DateTime("2020-04-27T09:00:00.000Z");
EventDateTime start = new EventDateTime()
.setDateTime(startDateTime)
.setTimeZone("Africa/Tunis");
event.setStart(start);
DateTime endDateTime = new DateTime("2020-04-27T10:30:00.000Z");
EventDateTime end = new EventDateTime()
.setDateTime(endDateTime)
.setTimeZone("Africa/Tunis");
event.setEnd(end);
List<EventAttendee> attendees = new ArrayList<EventAttendee>();
EventAttendee ens = new EventAttendee().setEmail("[email protected]");
attendees.add(ens);
event.setAttendees(attendees);
String calendarId = "primary";
event = service.events().insert(calendarId, event).execute();
但是我遇到了例外:
您能告诉我我错过了什么吗?。
非常感谢
APIs & Services
-> Credentials
+ CREATE CREDENTIALS
-> Service Account
Service account name
并单击Create
Create key
并选择JSON
(也可以使用p12,但是您需要以不同的方式构建GoogleCredential
json
文件将下载到您的计算机中它看起来如下:
{
"type": "service_account",
...
您正在使用的json文件不是用于服务帐户的正确文件,它没有指定字段type
-因此错误'type' field not specified
。