我正在试图向特定的URL发送PUT请求,但至今未能成功。
如果我通过HTTP请求GUI(例如这个),在以下URL上进行PUT操作即可:
http://www.mywebsite.com:port/Application?key=apikey&id=id&option=enable|disable
注意,上面的请求中指定了一个端口号,在通过Ruby代码提交请求时,我也需要这样做。
如何在Ruby中复制此类请求?
我正在试图向特定的URL发送PUT请求,但至今未能成功。
如果我通过HTTP请求GUI(例如这个),在以下URL上进行PUT操作即可:
http://www.mywebsite.com:port/Application?key=apikey&id=id&option=enable|disable
注意,上面的请求中指定了一个端口号,在通过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的回答帮助我找对了方向。再多挖掘一些资料,我找到了一个更优雅的解决方案,受到这个答案的指导。
http = Net::HTTP.new('www.mywebsite.com', port)
response = http.send_request('PUT', '/path/from/host?id=id&option=enable|disable')
send_request
需要三个参数,第三个参数是你要 'PUT' 的数据。为了让内容更加通俗易懂,我可以这么翻译:在使用 send_request
时,需要提供三个参数,其中第三个参数为你想要进行 'PUT' 操作的数据。 - rampion