关闭。但实际上您在 POST 请求的标头字段中缺少一项重要数据。即,该行:
Content-Type: application/json
使您的整个请求成为:
POST /<Calendar-Id-Redacted> HTTP/1.1
Host: localhost
User-Agent: Racket/6.5.0.5 (net/http-client)
Content-Length: 116
Authorization: Bearer <Key-Redacted>
Content-Type: application/json
{
"end": {
"dateTime": "2016-05-30T14:00:00-04:00"
},
"start": {
"dateTime": "2016-05-30T13:00:00-04:00"
}
}
由于某种原因,如果您丢失了它,Google 不会给您一个好的错误消息,但如果您确实有它,Google 将遵循 API 调用。
当你在curl中运行命令时,如果你像这样运行它(其中你有一个名为data.txt
其中包含您的 json 对象:
curl -X POST -d @data.txt https://www.googleapis.com/calendar/v3/calendars/<Calendar-Id-Redacted>/events --header 'Authorization: Bearer <Key-Redacted>'
它会失败。但是如果你添加标题--header "Content-Type: application/json"
,API 将按预期工作:
curl -X POST -d @data.txt https://www.googleapis.com/calendar/v3/calendars/<Calendar-Id-Redacted>/events --header 'Authorization: Bearer <Key-Redacted>' --header "Content-Type: application/json"
将该标头添加到您拥有的库中只需对生成发布请求的函数进行一项修改:
(define (json-api-post u b
#:token [t #f]
#:headers [headers '("Content-Type: application/json")])
....)
它与您之前的完全相同,只是我们修改了 headers 字段以包含(默认情况下)包含字符串的列表:"Content-Type: application/json"
。通过此更改,Google 应该接受您的 API。 (请注意,还有很多其他方法可以修改 headers 函数,这只是一种简单的方法。)
将它们放在一起,您的最终代码应该类似于:
(define (insert-events calendar-id
event
#:token [t #f]
#:max-attendees [max-attendees #f]
#:send-notifications [send-notifications #f]
#:supports-attachments [supports-attachments #f])
(json-api-post (string->url
(format
"https://www.googleapis.com/calendar/v3/calendars/~a/events"
(form-urlencoded-encode calendar-id)))
event
#:token t))
(define (json-api-post u b
#:token [t #f]
#:headers [headers '("Content-Type: application/json")])
(define b* (jsexpr->bytes b))
(let retry ([t t]
[retry-counter 0])
(parse-json-response
(POST-string u b* (if t (cons (token->authorization-header t) headers) headers))
retry
t
retry-counter)))
(define (POST-string u b headers)
(port->string (post-pure-port u b headers)))
希望有帮助。