Ruby send JSON request

后端 未结 10 1345
后悔当初
后悔当初 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:11

    require 'net/http'
    require 'json'
    
    def create_agent
        uri = URI('http://api.nsa.gov:1337/agent')
        http = Net::HTTP.new(uri.host, uri.port)
        req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')
        req.body = {name: 'John Doe', role: 'agent'}.to_json
        res = http.request(req)
        puts "response #{res.body}"
    rescue => e
        puts "failed #{e}"
    end
    

提交回复
热议问题