创建事件时,Google Calendar API v3始终返回BadRequest 答案:修复:参考文献:

问题描述

我创建了共享日历,并希望向日历中添加事件。

我创建了一个项目并设置了服务帐户[email protected]

然后,我以所有者的身份将日历共享到服务帐户。

然后我注意到

服务帐户必须手动添加共享日历

如此处所述 https://stackoverflow.com/a/62232361/298430https://issuetracker.google.com/issues/148804709

所以我写了一个代码

 @Test
  fun addCalendarToServiceAccount() {

    val calList1: CalendarList = calendar.calendarList().list().execute()
    logger.info("calList1 = {}",calList1)

    val inserted = calendar.calendarList().insert(CalendarListEntry().setId(calendarId)).execute()
    logger.info("inserted = {}",inserted)

    val calList2: CalendarList = calendar.calendarList().list().execute()
    logger.info("calList2 = {}",calList2)
  }

它完美地工作。初次打电话时,我看到calList1为空,并且calList2包含某些内容

然后我将一个事件手动插入日历(使用Google日历WEB UI),我想检查是否可以检索该事件:

@Test
  fun listEvents() {
    val events: Events = calendar.events().list(calendarId).execute()
    logger.info("events = {}",events)
    events.items.forEachIndexed { index,e ->
      logger.info("Event [index = {}],event = {}",index,e)
    }
  }

它也可以。

{
   "accessRole":"owner","defaultReminders":[

   ],"etag":"\"xxx\"","items":[
      {
         "created":"2020-08-17T17:51:21.000Z","creator":{
            "email":"[email protected]"
         },"end":{
            "date":"2020-08-20"
         },"htmlLink":"https://www.google.com/calendar/event?eid=xxx","iCalUID":"[email protected]","id":"xxx","kind":"calendar#event","organizer":{
            "displayName":"xxx","email":"[email protected]","self":true
         },"reminders":{
            "useDefault":false
         },"sequence":0,"start":{
            "date":"2020-08-19"
         },"status":"confirmed","summary":"xxx  test1","transparency":"transparent","updated":"2020-08-18T01:07:54.441Z"
      }
   ],"kind":"calendar#events","nextSyncToken":"xxx","summary":"xxx","timeZone":"Asia/Taipei","updated":"2020-08-18T01:07:54.688Z"
}

然后我要以编程方式插入一些内容,例如API示例所示:

@Test
  fun testInsertEvent() {
    val Now = LocalDateTime.Now().withSecond(0).withNano(0)
    val zoneId = ZoneId.of("Asia/Taipei")
    val fromDate = Date.from(Now.atZone(zoneId).toInstant())
    val endDate = Date.from(Now.plusMinutes(60).atZone(zoneId).toInstant())

    val event = Event()
      .setSummary("Google I/O 2015")
      .setLocation("800 Howard St.,San Francisco,CA 94103")
      .setDescription("A chance to hear more about Google's developer products.")
      .setStart(EventDateTime().setDate(DateTime(fromDate,TimeZone.getTimeZone(zoneId))))
      .setEnd(EventDateTime().setDate(DateTime(endDate,TimeZone.getTimeZone(zoneId))))

    logger.info("before insert event : {}",event)

    val eventResult: Event = calendar.events().insert(calendarId,event).execute()
    logger.info("eventResult = {}",eventResult)
  }

我可以看到客户端真正地POST到google'e端点:

Logs caught by IDEA

身体是:

{
   "description":"A chance to hear more about Google's developer products.","end":{
      "date":"2020-08-18T11:32:00.000+08:00"
   },"location":"800 Howard St.,CA 94103","start":{
      "date":"2020-08-18T10:32:00.000+08:00"
   },"summary":"Google I/O 2015"
}

但是google只是回答了400 BadRequest,没有任何进一步的描述:

2020-08-18 10:32:15.974 [main] INFO  c.g.a.c.h.HttpResponse - -------------- RESPONSE --------------
HTTP/1.1 400 Bad Request
transfer-encoding: chunked
Alt-Svc: h3-29=":443"; ma=2592000,h3-27=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"
Server: ESF
X-Content-Type-Options: nosniff
Pragma: no-cache
Date: Tue,18 Aug 2020 02:32:15 GMT
x-frame-options: SAMEORIGIN
Cache-Control: no-cache,no-store,max-age=0,must-revalidate
content-encoding: gzip
vary: Referer
vary: X-Origin
vary: Origin
Expires: Mon,01 Jan 1990 00:00:00 GMT
X-XSS-Protection: 0
Content-Type: application/json; charset=UTF-8

2020-08-18 10:32:15.980 [main] INFO  c.g.a.c.u.LoggingByteArrayOutputStream - Total: 171 bytes
2020-08-18 10:32:15.980 [main] INFO  c.g.a.c.u.LoggingByteArrayOutputStream - {
 "error": {
  "errors": [
   {
    "domain": "global","reason": "badRequest","message": "Bad Request"
   }
  ],"code": 400,"message": "Bad Request"
 }
}

我正在使用相同的 calendar 实例,可以成功addCalendarToServiceAccount()(作为owner)和listEvents()。 但是插入事件时出了什么问题?我有什么想念吗?

其他字段的初始化如下:

  @Value("\${google.calendar.id}")
  private lateinit var calendarId: String

  @Value("\${google.calendar.apiKey}")
  private lateinit var apiKey : String

  private val httpTransport: HttpTransport by lazy {
    GoogleNetHttpTransport.newTrustedTransport()
  }

  private val jacksonFactory: JsonFactory by lazy {
    JacksonFactory.getDefaultInstance()
  }

  private val saCredentials: GoogleCredentials by lazy {
    javaClass.getResourceAsstream("/chancer-d1de03c4c25a.json").use { iStream ->
      ServiceAccountCredentials.fromStream(iStream)
        .createScoped(listof(
          "https://www.googleapis.com/auth/cloud-platform",*CalendarScopes.all().toTypedArray()
        ))
    }.apply {
      refreshIfExpired()
    }
  }


  private val requestinitializer: HttpRequestinitializer by lazy {
    HttpCredentialsAdapter(saCredentials)
  }

  private val calendar: Calendar by lazy {
    Calendar.Builder(httpTransport,jacksonFactory,requestinitializer)
      .build()
  }

环境:

    <java.version>1.8</java.version>
    <kotlin.version>1.4.0</kotlin.version>


    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client</artifactId>
      <version>1.30.10</version>
    </dependency>
    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-calendar</artifactId>
      <version>v3-rev20200610-1.30.10</version>
    </dependency>
    <dependency>
      <groupId>com.google.auth</groupId>
      <artifactId>google-auth-library-oauth2-http</artifactId>
      <version>0.21.1</version>
    </dependency>

解决方法

答案:

您需要使用start.dateTimeend.dateTime而不是start.dateend.date

修复:

根据documentation

end.date:如果是全天活动,则格式为“ yyyy-mm-dd”的日期。

end.dateTime:时间,作为组合的日期时间值(根据RFC3339格式化)。除非在 timeZone 中明确指定了时区,否则需要时区偏移量。

start.date:如果是全天活动,则格式为“ yyyy-mm-dd”的日期。

start.dateTime:时间,作为组合的日期时间值(根据RFC3339格式化)。除非在 timeZone 中明确指定了时区,否则需要时区偏移量。

因此,您需要从以下日期和时间设置方法更改

EventDateTime().setDate(DateTime(fromDate,TimeZone.getTimeZone(zoneId))))

收件人:

EventDateTime().setDateTime(DateTime(fromDate,TimeZone.getTimeZone(zoneId))))

将请求正文更改为:

{
  "description": "A chance to hear more about Google's developer products.","end": {
      "dateTime": "2020-08-18T11:32:00.000+08:00" // modified
  },"location": "800 Howard St.,San Francisco,CA 94103","start": {
    "dateTime": "2020-08-18T10:32:00.000+08:00" // modified
  },"summary": "Google I/O 2015"
}

您可以查看此方法here的文档。

我希望这对您有帮助!

参考文献: