Rails通过rest-client发布到Google Calender API会给出错误的请求'错误

时间:2016-12-09 12:36:46

标签: ruby-on-rails ruby google-api google-calendar-api rest-client

我已经搜索了很多其他问题而且我没有看到我做了不同的事情,但是当尝试向Google API发布新活动时,其他客户端将无法正常工作

Case IntWhSales = 'Y' Then OrderQtyCurrent Else OrderQtyOrig End AS [OrderQuantity]

1 个答案:

答案 0 :(得分:1)

请注意,您可能有兴趣使用Google自己的Ruby客户端库而不仅仅是RestClient:

https://developers.google.com/api-client-library/ruby/start/installation

使用RestClient解决问题

您可以从HTTP 400异常中提取错误消息。

这就是我所看到的:

auth_header 'Bearer zzzz...'
base_url = 'https://www.googleapis.com/calendar/v3/calendars/primary'
event = {'summary': 'Test RestClient event', 'start': {'dateTime': Time.now.strftime('%FT%T%z')}, 'end': {'dateTime': (Time.now + 3600).strftime('%FT%T%z')}}

begin
  RestClient.post(base_url + '/events', event.to_json, {authorization: auth_header})
rescue RestClient::BadRequest => err
  puts err.response.body
end

打印此HTTP 400响应:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "parseError",
    "message": "This API does not support parsing form-encoded input."
   }
  ],
  "code": 400,
  "message": "This API does not support parsing form-encoded input."
 }
}

这里发生了什么?除非另有说明,否则RestClient假定您需要Content-Type application/x-www-form-urlencoded的请求。

因此,如果我们添加正确的Content-Type: application/json标头,一切都按预期工作:

>> RestClient.post(base_url + '/events', event.to_json, {authorization: auth_header, content_type: :json})
=> <RestClient::Response 200 "{\n \"kind\": ...">

删除了未解决问题的先前答案