Ruby:带有 JSON 主体的 PUT 请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4762541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby: PUT Request with JSON body?
提问by dpigera
I need to create an HTTP PUT requestusing ruby.
我需要使用 ruby创建一个HTTP PUT 请求。
The request has a JSON body
请求有一个JSON 正文
I was able to generate the JSON body using:
我能够使用以下方法生成 JSON 正文:
require 'rubygems'
require 'json'
jsonbody = JSON.generate["message"=>"test","user"=>"user1"]
I need to send this PUT request to the url:
我需要将此 PUT 请求发送到 url:
require 'open-uri'
url = URI.parse('http://www.data.com?access_token=123')
Can someone please tell me how I can do this in Ruby?
有人可以告诉我如何在 Ruby 中做到这一点吗?
回答by Lars Tackmann
Using restclient(gem install rest-client) like this:
像这样使用restclient(gem install rest-client):
require 'rubygems'
require 'rest_client'
require 'json'
jdata = JSON.generate(["test"])
RestClient.put 'http://localhost:4567/users/123', jdata, {:content_type => :json}
against the following sinatraservice:
针对以下sinatra服务:
require 'sinatra'
require 'json'
put '/users/:id' do |n|
data = JSON.parse(request.body.read)
"Got #{data} for user #{n}"
end
works on my computer.
在我的电脑上工作。
回答by Andy Lindeman
Easiest way is with Net::HTTP:
最简单的方法是Net::HTTP:
require 'net/http'
http = Net::HTTP.new('www.data.com')
response = http.request_put('/?access_token=123', jsonbody)

