使用Ruby的Net/HTTP模块,我是否可以发送原始JSON数据? [英] Using Ruby's Net/HTTP module, can I ever send raw JSON data?

查看:52
本文介绍了使用Ruby的Net/HTTP模块,我是否可以发送原始JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been doing a lot of research on the topic of sending JSON data through Ruby HTTP requests, compared to sending data and requests through Fiddler. My primary goal is to find a way to send a nested hash of data in an HTTP request using Ruby.

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

In Fiddler, you can specify a JSON in the request body and add the header "Content-Type: application/json".

在Ruby中,使用Net/HTTP,如果可能的话,我想做同样的事情.我预感这是不可能的,因为在Ruby中将JSON数据添加到http请求的唯一方法是使用评论在本文中.)

In Ruby, using Net/HTTP, I'd like to do the same thing if it's possible. I have a hunch that it isn't possible, because the only way to add JSON data to an http request in Ruby is by using set_form_data, which expects data in a hash. This is fine in most cases, but this function does not properly handle nested hashes (see the comments in this article).

有什么建议吗?

推荐答案

在阅读了以上tadman的答案之后,我更加仔细地研究了如何直接将数据添加到HTTP请求的主体中.最后,我确实做到了:

After reading tadman's answer above, I looked more closely at adding data directly to the body of the HTTP request. In the end, I did exactly that:

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($ stdout).这可能是调试通过Ruby发送的HTTP请求的最简单方法,而且很清楚发生了什么:)

If you ever want to debug the HTTP request being sent out, use this code, verbatim: http.set_debug_output( $stdout ). This is probably the easiest way to debug HTTP requests being sent through Ruby and it's very clear what is going on :)

这篇关于使用Ruby的Net/HTTP模块,我是否可以发送原始JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆