2016-04-27 36 views
2

与通过Fiddler发送数据和请求相比,我一直在通过Ruby HTTP请求发送JSON数据的主题进行了大量研究。 我的主要目标是找到一种方法来使用Ruby在HTTP请求中发送数据的嵌套散列。使用Ruby的Net/HTTP模块,我可以发送原始的JSON数据吗?

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

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

有什么建议吗?

回答

0

阅读上述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请求,使用此代码,逐字:http.set_debug_output($标准输出)。这可能是调试通过Ruby发送的HTTP请求的最简单方法,它非常清楚发生了什么:)

2

尽管使用类似Faraday往往是很多更愉快的,它仍然是可行的与网:: 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' 
) 
+0

谢谢。你的回答帮助我达成了一些有效的工作。 – Max

相关问题