Ruby https POST with headers

后端 未结 5 825
花落未央
花落未央 2020-12-08 02:38

How can I make a Https post with a header in Ruby with a json?

I have tried:

uri = URI.parse(\"https://...\")
    https = Net::HTTP.new(uri.host,uri.         


        
5条回答
  •  醉话见心
    2020-12-08 03:19

    Here's a cleaner way to use Net::HTTP. If you just want to get the response and throw other objects away this is quite useful.

    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.
    

提交回复
热议问题