91

如何在 ruby​​ 中发送 JSON 请求?我有一个 JSON 对象,但我认为我不能这样做.send。我必须让 javascript 发送表单吗?

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

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

4

10 回答 10

86
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
于 2014-01-21T15:56:26.797 回答
52
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
于 2014-05-15T11:26:46.263 回答
17

HTTParty使我认为这更容易一些(并且可以与嵌套的 json 等一起使用,这在我见过的其他示例中似乎不起作用。

require 'httparty'
HTTParty.post("http://localhost:3000/api/v1/users", body: {user: {email: 'user1@example.com', password: 'secret'}}).body
于 2013-01-24T00:39:01.710 回答
7

现实生活中的例子,通过 NetHttps通知Airbrake API 新的部署

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)

笔记:

如果您通过 Authorization header set headerreq['Authorization'] = "Token xxxxxxxxxxxx"http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html进行身份验证

于 2016-09-05T10:21:38.710 回答
5

这适用于带有 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
于 2019-03-11T12:30:29.643 回答
3

对于那些需要它的人来说,一个简单的 json POST 请求示例比 Tom 链接的内容更简单:

require 'net/http'

uri = URI.parse("http://www.example.com/search.json")
response = Net::HTTP.post_form(uri, {"search" => "Berlin"})
于 2012-08-28T10:39:46.160 回答
3

我喜欢这个名为 `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
于 2016-04-05T15:26:19.367 回答
2

现在是 2020 年 - 没有人应该再使用Net::HTTP了,所有答案似乎都这么说,使用更高级的 gem,比如 Faraday - Github


也就是说,我喜欢做的是围绕 HTTP api 调用的包装器,这就是所谓的

rv = Transporter::FaradayHttp[url, options]

因为这允许我在没有额外依赖的情况下伪造 HTTP 调用,即:

  if InfoSig.env?(:test) && !(url.to_s =~ /localhost/)
    response_body = FakerForTests[url: url, options: options]

  else
    conn = Faraday::Connection.new url, connection_options

伪造者看起来像这样的地方

我知道有 HTTP 模拟/存根框架,但至少当我上次研究时,它们不允许我有效地验证请求,它们只是用于 HTTP,而不是例如原始 TCP 交换,这个系统允许我有一个所有 API 通信的统一框架。


假设您只想快速&脏地将散列转换为 json,将 json 发送到远程主机以测试 API 并解析对 ruby​​ 的响应,这可能是最快的方法,无需额外的 gem:

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

希望这是不言而喻的,但不要在生产中使用它。

于 2013-11-19T14:11:50.130 回答
1

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
于 2015-05-22T03:13:05.283 回答
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'
于 2016-07-16T21:35:39.057 回答