【问题标题】:Ruby Typhoeus gem - Invalid Json in body?Ruby Typhoeus gem - 体内的 Json 无效?
【发布时间】:2014-01-20 03:27:25
【问题描述】:

我有以下代码:

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 有问题。

【问题讨论】:

    标签: ruby json typhoeus


    【解决方案1】:

    我猜您可能需要使用 Oj (https://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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-17
      相关资源
      最近更新 更多