Ruby发送JSON请求

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

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

用标题 – 内容types= JSON和正文的JSON对象?

 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 
 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 

HTTParty使这个更容易一些,我认为(和嵌套的JSON等工作,这似乎并没有在我见过的其他例子中工作。

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

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

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

假设你只是想快速和脏的哈希转换为JSON,将JSON发送到远程主机来testingAPI和parsing对Ruby的响应这可能是最快的方式,而不涉及额外的gem:

 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/

我喜欢这个重量轻的HTTP请求客户端,称为“unirest”

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 

真实生活的例子,通过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 header req['Authorization'] = "Token xxxxxxxxxxxx"http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html进行身份validation

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 
 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' 

你可以像这样发送json数据数组:

 require 'rest_client' postData = Net::HTTP.post_form(URI.parse('http://www.xyz.com/api/valueoff'), {'data'=>jsonData}) 

你应该有这个rest_client gem。