【发布时间】:2011-09-28 19:40:40
【问题描述】:
我对 ruby 非常陌生,并且尝试了一些基本的东西。当我使用以下方式向服务器发送 HTTP 请求时:
curl -v -H "Content-Type: application/json" -X GET -d "{"myrequest":"myTest","reqid":"44","data":{"name":"test"}}" localhost:8099
我的服务器将 JSON 数据视为 "{myrequest:myTest,reqid:44,data:{name:test}}"
但是当我使用以下 ruby 代码发送请求时:
require 'net/http'
@host = 'localhost'
@port = '8099'
@path = "/posts"
@body = ActiveSupport::JSON.encode({
:bbrequest => "BBTest",
:reqid => "44",
:data =>
{
:name => "test"
}
})
request = Net::HTTP::Post.new(@path, initheader = {'Content-Type' =>'application/json'})
request.body = @body
response = Net::HTTP.new(@host, @port).start {|http| http.request(request) }
puts "Response #{response.code} #{response.message}: #{response.body}"
它认为它是 "{\"bbrequest\":\"BBTest\",\"reqid\":\"44\",\"data\":{\"name\":\ " test\"}}" 并且服务器无法解析它。也许我需要设置一些额外的选项来从 Ruby 发送请求以排除这些额外的字符?
你能帮忙吗?提前致谢。
【问题讨论】:
-
不是您的问题的答案,但使用 RestClient 应该可以减少您需要做的工作量,而且我知道它可以轻松发送 JSON:github.com/archiloque/rest-client
-
JSON.parse("{\"bbrequest\":\"BBTest\",\"reqid\":\"44\",\"data\":{\"name\":\" test\"}}")工作正常你确定你在解析这个字符串吗? -
你确定问题是转义字符被发送到服务器,而不仅仅是 irb 或 inspect 输出?因为您显示的代码没有放入这些字符。
标签: ruby-on-rails ruby ruby-on-rails-3