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

时间:2022-03-08 20:15:34

I am trying to send a PUT request to a particular URL, and have thus far been unsuccessful in doing so.

我试图发送一个PUT请求到一个特定的URL,并且到目前为止没有成功。

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(例如这个GUI)来实现这个功能,那么只需在以下url上执行一个PUT即可:

http://www.mywebsite.com:port/Application?key=apikey&id=id&option=enable|disable

http://www.mywebsite.com应用程序?关键= apikey&id = id选项=启用|禁用

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

1 个解决方案

#1


23  

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

#1


23  

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