1

我有以下代码:

require 'Typhoeus'

  url = Typhoeus::Request.new("https://fluidsurveys.com/api/v2/webhooks/subscribe/",
        userpwd: "username_test:password_test",
        method: :post,
        body: {
             'subscription_url' => 'http://glacial-spire-test.herokuapp.com/hooks/response_created_callback',
             'event' => 'response_complete'
        },
        headers: { 'Content-Type' => "application/json"})

    response = url.run.body
    puts response

这将返回一个响应代码400和一个错误:

Content-Type set to application/json but could not decode valid JSON in request body.

以下是我正在进行的 API 调用的文档:http: //docs.fluidsurveys.com/api/webhooks.html

POST /api/v2/webhooks/subscribe/¶
Returns a status of 409 if a webhook with the subscription url already exists. Returns a       
status of 201 if the webhook was successfully created. Requests must be sent as an 
application/json-encoded dictionary with the required fields subscription_url and event

样品请求(根据文档):

{
  "subscription_url": "http://fluidsurveys.com/api/v2/callback/",
  "event": "response_complete",
  "survey": 1,
  "collector": 1
}

我在这里做错了什么?调查和收集器是可选参数,我没有看到我体内的 json 有问题。

4

1 回答 1

3

我猜您可能需要使用Ojhttps://github.com/ohler55/oj)之类的库将请求正文转换为 JSON。使用Oj库:

requestBody = {
  'subscription_url' => 'http://glacial-spire-test.herokuapp.com/hook/response_created_callback',
  'event' => 'response_complete'
}

url = Typhoeus::Request.new("https://fluidsurveys.com/api/v2/webhooks/subscribe/",
        userpwd: "username_test:password_test",
        method: :post,
        body: Oj.dump(requestBody, mode: :compat),
        headers: { 'Content-Type' => "application/json"})

response = url.run.body
puts response

关键线是:

        body: Oj.dump(requestBody, mode: :compat)

如果您需要将任何 JSON 内容加载到 Ruby,只需使用Oj.load

于 2014-01-20T05:10:35.350 回答