【问题标题】:Http JSON POST request returns empty body response with rubyHttp JSON POST 请求返回带有 ruby​​ 的空正文响应
【发布时间】:2015-12-02 17:24:07
【问题描述】:

我在玩 ruby​​ 和服务,我尝试检索一个 json 响应,但只得到一个空的正文响应:

uri = URI("http://.../v1/queryContext")
req = Net::HTTP::Post.new(uri.path, initheader = {'content-type' => 'application/json', 'Accept' => 'application/json'})
req.body = {
           "entities": [
           {
               "type": "Printer",
               "isPattern": "false",
               "id": "UM1"
           }
       ]
       }.to_json
       response = Net::HTTP.start(uri.hostname, uri.port) do |http|
         http.request(req)
       end

请求工作正常(状态 200 / 消息正常),但返回的 JSON 内容不存在(response.body.size = 0)。很奇怪,我可以看到它是由服务器生成的。

Response payload: '{
  "contextResponses" : [
    {
      "contextElement" : {
        "type" : "Printer",
        "isPattern" : "false",
        "id" : "UM1",
        "attributes" : [
          {
            "name" : "bed",
            "type" : "float",
            "value" : "50"
          },
          {
            "name" : "temperature",
            "type" : "float",
            "value" : "180"
          }
        ]
      },
      "statusCode" : {
        "code" : "200",
        "reasonPhrase" : "OK"
      }
    }
  ]
}
'

此外,以下 curl 等效项可以正常工作:

(curl http://.../v1/queryContext -s -S --header 'Content-Type: application/json' \
    --header 'Accept: application/json' -d @- | python -mjson.tool) <<EOF
{
    "entities": [
        {
            "type": "Printer",
            "isPattern": "false",
            "id": "UM1"
        }
    ]
} 
EOF

我在使用 httpclient 或 unirest 等 gem 时遇到了同样的问题。 Ruby 中是否有什么特别的事情需要做才能接收等待的 json 内容?

谢谢

【问题讨论】:

  • 好的,知道了。它与在函数中运行的响应的范围有关,即使其他值很好(response.status 和 response.message),response.body 也会从函数中丢失。

标签: ruby-on-rails ruby json fiware-orion


【解决方案1】:

您的代码看起来不错,我建议清除捆绑包的缓存 (bundle clean --force) 并重新安装包。

您是否也尝试在另一台机器上运行它?

顺便说一下,这是一个关于使用您正在使用的 HTTP 库执行 json 请求的清晰示例: https://www.socialtext.net/open/very_simple_rest_in_ruby_part_3_post_to_create_a_new_workspace

【讨论】:

  • 谢谢,是的,我在另一台机器上试过,得到了同样的结果。我还尝试了来自服务器的 localhost 连接。
【解决方案2】:

您的请求的正文似乎格式化得很漂亮。如果您使用对象映射器或等。您能否检查一下您的对象映射器是否启用了 prettyprint 属性或类似的东西?如果已启用,请将其删除并重试。如果您不使用对象映射器,请尝试发送紧凑的正文而不是格式化的正文。

祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    相关资源
    最近更新 更多