如何在ruby中发送JSON请求?我有一个JSON对象,但我认为我做不到.send
。我必须要用JavaScript发送表格吗?
还是可以在ruby中使用net / http类?
与标头-内容类型= json和正文json对象?
Answers:
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
http.request(req).read_body
阅读响应正文。大!
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
真实示例,通过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标头集标头req['Authorization'] = "Token xxxxxxxxxxxx"
或http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html进行身份验证
一个简单的json POST请求示例,针对那些需要它的人,甚至比Tom链接到的内容更简单:
require 'net/http'
uri = URI.parse("http://www.example.com/search.json")
response = Net::HTTP.post_form(uri, {"search" => "Berlin"})
到了2020年-没人应该再使用它Net::HTTP
了,所有答案似乎都这么说,请使用更高级别的宝石,例如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}'`
希望这不用说,但是不要在生产中使用它。
Net::HTTP
”断言
nobody should be using Net::HTTP any more
投票
这适用于使用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
我喜欢这个名为“ 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
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
Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |client|
req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})