带标题的Ruby https POST

cof*_*fee 32 ruby https post header

如何在带有json的Ruby中使用标题创建一个Https帖子?

我试过了:

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
Run Code Online (Sandbox Code Playgroud)

cof*_*fee 53

问题是json.这解决了我的问题.无论如何,我的问题不明确,所以赏金给了Juri

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}"
Run Code Online (Sandbox Code Playgroud)

  • 代码不知何故对我不起作用。而不是 @toSend={}.to_json,我必须执行 req.set_form_data(@toSend) 才能正确发送我的数据。希望这会帮助其他陷入困境的人。 (2认同)
  • 它应该是`initheader: {'Content-Type' =>'application/json'}` (2认同)

Jur*_*ass 36

尝试:

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
Run Code Online (Sandbox Code Playgroud)

  • 如何设置正文和标题? (2认同)

dar*_*123 13

这是一种使用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.
Run Code Online (Sandbox Code Playgroud)


Ste*_*oka 10

默认安全示例:

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) }
Run Code Online (Sandbox Code Playgroud)