如何在 Ruby 中发送 HTTP PUT 请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11403728/
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
How can I send an HTTP PUT request in Ruby?
提问by finiteloop
I am trying to send a PUT request to a particular URL, and have thus far been unsuccessful in doing so.
我正在尝试向特定 URL 发送 PUT 请求,但迄今为止没有成功。
If I were doing it through an HTTP requester GUI, such as thisone, it would be as simple as doing a PUT on the following url:
如果我是通过 HTTP 请求者 GUI 来完成的,比如这个,它就像在以下 url 上执行 PUT 一样简单:
http://www.mywebsite.com:port/Application?key=apikey&id=id&option=enable|disable
http://www.mywebsite.com:port/Application?key=apikey&id=id&option=enable|disable
Note that a port number is specified in the above request. I will also need to do that when submitting the request through the ruby code.
请注意,在上述请求中指定了端口号。在通过 ruby 代码提交请求时,我也需要这样做。
How can I replicate such a request in Ruby?
如何在 Ruby 中复制这样的请求?
回答by Larry OBrien
require 'net/http'
port = 8080
host = "127.0.0.1"
path = "/Application?key=apikey&id=id&option=enable"
req = Net::HTTP::Put.new(path, initheader = { 'Content-Type' => 'text/plain'})
req.body = "whatever"
response = Net::HTTP.new(host, port).start {|http| http.request(req) }
puts response.code
Larry's answer helped point me in the right direction. A little more digging helped me find a more elegant solution guided by this answer.
拉里的回答帮助我指明了正确的方向。多一点挖掘帮助我找到了一个更优雅的解决方案,以这个答案为指导。
http = Net::HTTP.new('www.mywebsite.com', port)
response = http.send_request('PUT', '/path/from/host?id=id&option=enable|disable')

