Ruby send JSON request

后端 未结 10 1305
后悔当初
后悔当初 2020-11-28 20:37

How do I send a JSON request in ruby? I have a JSON object but I dont think I can just do .send. Do I have to have javascript send the form?

Or can I us

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 21:15

    This works on ruby 2.4 HTTPS Post with JSON object and the response body written out.

    require 'net/http' #net/https does not have to be required anymore
    require 'json'
    require 'uri'
    
    uri = URI('https://your.secure-url.com')
    Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
      request = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
      request.body = {parameter: 'value'}.to_json
      response = http.request request # Net::HTTPResponse object
      puts "response #{response.body}"
    end
    

提交回复
热议问题