简体   繁体   English

如何在Ruby中发送HTTP PUT请求?

[英]How can I send an HTTP PUT request in Ruby?

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 this one, 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

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中复制这样的请求?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM