Ruby发送JSON请求

And*_*ndy 80 ruby json httprequest

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

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

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

Car*_*lZA 72

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
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢你的建议,使用URI来处理主机名和端口,否则这是非常繁琐的.但你忘了在Post.new(...)中设置uri.path:`req = Net :: HTTP :: Post.new(uri.path,initheader = {'Content-Type'=>'application/json' })` (7认同)

neo*_*eye 46

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
Run Code Online (Sandbox Code Playgroud)

  • 对于https请求,只需添加:http.use_ssl = true. (4认同)

Bri*_*ong 16

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

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


sza*_*see 8

这适用于带有 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
Run Code Online (Sandbox Code Playgroud)


Chr*_*fer 7

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

require 'net/http'

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

  • 看起来它应该可以工作,但是post_form会将参数转换为?key = value&key = value语法.如果你想在请求体设置为JSON字符串的情况下进行POST,我认为你需要一个不同的解决方案. (14认同)
  • 从根本上讲,这不是JSON请求。这是一个未编码的身体。没有JSON。标头甚至说了很多。这永远不会与任何示例一起使用。 (2认同)
  • 这个答案是不正确的。这是mime / multipart中的POST,指向其中写有“ json”的网址。 (2认同)

equ*_*nt8 6

现实生活中的例子,通过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)
Run Code Online (Sandbox Code Playgroud)

笔记:

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