【发布时间】: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