如何使用JSON在Ruby中創建一個Https標題?Ruby帶標題的POST POST
我曾嘗試:
uri = URI.parse("https://...")
https = Net::HTTP.new(uri.host,uri.port)
req = Net::HTTP::Post.new(uri.path)
req['foo'] = bar
res = https.request(req)
puts res.body
如何使用JSON在Ruby中創建一個Https標題?Ruby帶標題的POST POST
我曾嘗試:
uri = URI.parse("https://...")
https = Net::HTTP.new(uri.host,uri.port)
req = Net::HTTP::Post.new(uri.path)
req['foo'] = bar
res = https.request(req)
puts res.body
這是一個JSON的問題。這解決了我的問題。不管怎樣,我的問題是不明確的,所以賞金去樹裏
require 'uri'
require 'net/http'
require 'net/https'
require 'json'
@toSend = {
"date" => "2012-07-02",
"aaaa" => "bbbbb",
"cccc" => "dddd"
}.to_json
uri = URI.parse("https:/...")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})
req['foo'] = 'bar'
req.body = "[ #{@toSend} ]"
res = https.request(req)
puts "Response #{res.code} #{res.message}: #{res.body}"
代碼莫名其妙地不適合我。而不是@toSend = {}。to_json,我不得不做req.set_form_data(@toSend)來正確發送我的數據。希望這會幫助其他陷入困境的人。 – Kirk
我不需要使用HTTPS,但在這裏找到了一個自定義標題的工作解決方案:http://stackoverflow.com/a/36928680/396429 –
它應該是'initheader:{'Content-Type'=>'application/json'}' –
嘗試:
require 'net/http'
require 'net/https'
uri = URI.parse("https://...")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(uri.path)
req['foo'] = bar
res = https.request(req)
puts res.body
我該如何設置正文和標題? –
'req.body =「身體」' –
一個安全,通過默認例如:
require 'net/http'
require 'net/https'
req = Net::HTTP::Post.new("/some/page.json", {'Content-Type' =>'application/json'})
req.body = your_post_body_json_or_whatever
http = Net::HTTP.new('www.example.com', 443)
http.use_ssl = true
http.ssl_version = :TLSv1 # ruby >= 2.0 supports :TLSv1_1 and :TLSv1_2.
# SSLv3 is broken at time of writing (POODLE), and it's old anyway.
http.verify_mode = OpenSSL::SSL::VERIFY_PEER # please don't use verify_none.
# if you want to verify a server is from a certain signing authority,
# (self-signed certs, for example), do this:
http.ca_file = 'my-signing-authority.crt'
response = http.start {|http| http.request(req) }
我該如何設置正文和標題? –
{'Content-Type'=>'application/json'}是成爲標題的哈希。 「your_post_body_json_or_whatever」是你的身體。 –
下面是使用Net :: HTTP一個更清潔的方式。如果你只是想得到迴應並扔掉其他物體,這是非常有用的。
require 'net/http'
require 'json'
uri = URI("https://example.com/path")
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = 'application/json'
# The body needs to be a JSON string, use whatever you know to parse Hash to JSON
req.body = {a: 1}.to_json
http.request(req)
end
# The "res" is what you need, get content from "res.body". It's a JSON string too.
它的工作,你可以傳遞數據和標題是這樣的:
header = {header part}
data = {"a"=> "123"}
uri = URI.parse("https://anyurl.com")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(uri.path, header)
req.body = data.to_json
res = https.request(req)
puts "Response #{res.code} #{res.message}: #{res.body}"
什麼錯誤? –