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

fin*_*oop 18 ruby rest http put

我正在尝试向特定的URL发送PUT请求,并且到目前为止还没有成功.

如果我通过HTTP请求者GUI(例如这个)执行此操作,那么就像在以下URL上执行PUT一样简单:

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

请注意,在上述请求中指定了端口号.通过ruby代码提交请求时,我还需要这样做.

我怎样才能在Ruby中复制这样的请求?

Lar*_*ien 31

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
Run Code Online (Sandbox Code Playgroud)

拉里的回答帮助我指明了正确的方向.多一点挖掘帮助我找到了这个答案引导的更优雅的解决方案.

http = Net::HTTP.new('www.mywebsite.com', port)
response = http.send_request('PUT', '/path/from/host?id=id&option=enable|disable')
Run Code Online (Sandbox Code Playgroud)

  • @finiteloop:`send_request`为你'PUT'的数据取第三个参数 (4认同)
  • 拉里,这非常有帮助.感谢您抽出宝贵时间来做到这一点. (3认同)