如何在ruby中发送JSON请求?我有一个JSON对象,但我想我不能只做.send
。我必须让javascript发送表单吗?
或者我可以使用ruby中的net/http类吗?
使用header - content type = json和body作为json对象?
发布于 2014-01-21 23:56:27
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-05-15 19:26: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
发布于 2013-01-24 08:39:02
我认为HTTParty让这件事变得更容易了(并且可以与嵌套的json等一起使用,这在我见过的其他示例中似乎不起作用。
require 'httparty'
HTTParty.post("http://localhost:3000/api/v1/users", body: {user: {email: 'user1@example.com', password: 'secret'}}).body
https://stackoverflow.com/questions/2024805
复制相似问题