使用Ruby的Net / HTTP模块,我可以发送原始JSON数据吗?

与通过Fiddler发送数据和请求相比,我一直在研究通过Ruby HTTP请求发送JSON数据的主题。 我的主要目标是找到一种方法,使用Ruby在HTTP请求中发送嵌套的数据哈希。

在Fiddler中,您可以在请求正文中指定JSON并添加标题“Content-Type:application / json”。

在Ruby中,使用Net / HTTP,如果可能,我想做同样的事情。 我有一种预感,这是不可能的,因为在Ruby中将JSON数据添加到http请求的唯一方法是使用set_form_data ,它需要哈希中的数据。 在大多数情况下这很好,但是这个函数没有正确处理嵌套的哈希值(参见本文中的注释 )。

有什么建议?

虽然使用像法拉第这样的东西通常更令人愉快,但它仍然适用于Net :: HTTP库:

require 'uri' require 'json' require 'net/http' url = URI.parse("http://example.com/endpoint") http = Net::HTTP.new(url.host, url.port) content = { test: 'content' } http.post( url.path, JSON.dump(content), 'Content-type' => 'application/json', 'Accept' => 'text/json, application/json' ) 

在阅读上面的tadman答案之后,我更仔细地研究了将数据直接添加到HTTP请求的主体。 最后,我做到了这一点:

 require 'uri' require 'json' require 'net/http' jsonbody = '{ "id":50071,"name":"qatest123456","pricings":[ {"id":"dsb","name":"DSB","entity_type":"Other","price":6}, {"id":"tokens","name":"Tokens","entity_type":"All","price":500} ] }' # Prepare request url = server + "/v1/entities" uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) http.set_debug_output( $stdout ) request = Net::HTTP::Put.new(uri ) request.body = jsonbody request.set_content_type("application/json") # Send request response = http.request(request) 

如果您想调试发送的HTTP请求,请使用以下代码: httpset.debug_output($ stdout) 。 这可能是调试通过Ruby发送的HTTP请求的最简单方法,而且非常清楚发生了什么:)