我有以下嵌套哈希:
$installation_settings = {
:lat => "43.107044",
:lon => "25.194757",
:country => "Poland",
:collector_installation => {
:people => 3,
:deviation_from_s => 5,
:solar_collector_id => 1,
:collectors_number => 2,
:monthly_water_consumption => 6000,
:gas_price => 0.09,
:electricity_price => 0.87
}
}
我正试图通过ruby发送帖子:
url = "someURL"
uri = URI(url)
res = Net::HTTP.post_form(uri, $installation_settings)
puts res.body
Net :: HTTP.post_form只允许发送简单的哈希(没有嵌套),所以我最终得到带有反斜杠的字符串。
我该如何发送?
答案 0 :(得分:1)
The docs说哈希必须是string: string
格式。所以嵌套的哈希看起来像:
Net::HTTP.post_form(URI('http://localhost'), 'a': { 'b': '2' })
=> #<Net::HTTPOK 200 OK readbody=true>
答案 1 :(得分:0)
我正在使用Ruby的旧版本,所以很遗憾我无法应用Anthony的答案。但是,我找到了另一个可能对某人有帮助的解决方案:
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = false
request = Net::HTTP::Post.new(uri.path, {'Content-Type' =>'application/json'})
request.body = installation_hash.to_json
response = http.request(request)