Ruby发送JSON请求

时间:2010-01-08 00:58:16

标签: ruby json httprequest

如何在ruby中发送JSON请求?我有一个JSON对象,但我不认为我可以做.send。我是否必须使用javascript发送表单?

或者我可以在ruby中使用net / http类吗?

使用header - content type = json和body json对象?

10 个答案:

答案 0 :(得分:70)

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

答案 1 :(得分:42)

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

答案 2 :(得分:16)

HTTParty让我觉得这更容易(并且适用于嵌套的json等,这在我见过的其他例子中似乎没有用。

require 'httparty'
HTTParty.post("http://localhost:3000/api/v1/users", body: {user: {email: 'user1@example.com', password: 'secret'}}).body

答案 3 :(得分:6)

一个简单的json POST请求示例,用于那些需要它的人甚至比Tom链接到的更简单:

require 'net/http'

uri = URI.parse("http://www.example.com/search.json")
response = Net::HTTP.post_form(uri, {"search" => "Berlin"})

答案 4 :(得分:6)

现实生活中的例子,通过NetHttps

通知Airbrake API about new deployment
require 'uri'
require 'net/https'
require 'json'

class MakeHttpsRequest
  def call(url, hash_json)
    uri = URI.parse(url)
    req = Net::HTTP::Post.new(uri.to_s)
    req.body = hash_json.to_json
    req['Content-Type'] = 'application/json'
    # ... set more request headers 

    response = https(uri).request(req)

    response.body
  end

  private

  def https(uri)
    Net::HTTP.new(uri.host, uri.port).tap do |http|
      http.use_ssl = true
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end
  end
end

project_id = 'yyyyyy'
project_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
url = "https://airbrake.io/api/v4/projects/#{project_id}/deploys?key=#{project_key}"
body_hash = {
  "environment":"production",
  "username":"tomas",
  "repository":"https://github.com/equivalent/scrapbook2",
  "revision":"live-20160905_0001",
  "version":"v2.0"
}

puts MakeHttpsRequest.new.call(url, body_hash)

注意:

如果您通过授权标头集标头req['Authorization'] = "Token xxxxxxxxxxxx"http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html

进行身份验证

答案 5 :(得分:5)

假设您只想快速和脏地将哈希转换为json,请将json发送到远程主机以测试API并解析对ruby的响应,这可能是最快的方式,而不涉及其他宝石:

JSON.load `curl -H 'Content-Type:application/json' -H 'Accept:application/json' -X POST localhost:3000/simple_api -d '#{message.to_json}'`

希望这不用说,但不要在生产中使用它。尝试法拉第宝石,米斯拉夫给出了一个令人信服的论据:http://mislav.uniqpath.com/2011/07/faraday-advanced-http/

答案 6 :(得分:2)

我喜欢这个名为`unirest'

的轻量级http请求客户端

gem install unirest

用法:

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

答案 7 :(得分:1)

这在使用JSON对象并写出响应正文的ruby 2.4 HTTPS Post上有效。

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

答案 8 :(得分:0)

net / http api可能难以使用。

require "net/http"

uri = URI.parse(uri)

Net::HTTP.new(uri.host, uri.port).start do |client|
  request                 = Net::HTTP::Post.new(uri.path)
  request.body            = "{}"
  request["Content-Type"] = "application/json"
  client.request(request)
end

答案 9 :(得分:0)

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'