Ruby send JSON request

后端 未结 10 1206
后悔当初
后悔当初 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:21
    data = {a: {b: [1, 2]}}.to_json
    uri = URI 'https://myapp.com/api/v1/resource'
    https = Net::HTTP.new uri.host, uri.port
    https.use_ssl = true
    https.post2 uri.path, data, 'Content-Type' => 'application/json'
    
    0 讨论(0)
  • 2020-11-28 21:22

    A simple json POST request example for those that need it even simpler than what Tom is linking to:

    require 'net/http'
    
    uri = URI.parse("http://www.example.com/search.json")
    response = Net::HTTP.post_form(uri, {"search" => "Berlin"})
    
    0 讨论(0)
  • 2020-11-28 21:24

    I like this light weight http request client called `unirest'

    gem install unirest

    usage:

    response = Unirest.post "http://httpbin.org/post", 
                            headers:{ "Accept" => "application/json" }, 
                            parameters:{ :age => 23, :foo => "bar" }
    
    response.code # Status code
    response.headers # Response headers
    response.body # Parsed body
    response.raw_body # Unparsed body
    
    0 讨论(0)
  • 2020-11-28 21:27
    uri = URI('https://myapp.com/api/v1/resource')
    req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
    req.body = {param1: 'some value', param2: 'some other value'}.to_json
    res = Net::HTTP.start(uri.hostname, uri.port) do |http|
      http.request(req)
    end
    
    0 讨论(0)
提交回复
热议问题