如何在Ruby中发送HTTP PUT请求? [英] How can I send an HTTP PUT request in Ruby?

查看:180
本文介绍了如何在Ruby中发送HTTP PUT请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如果我是通过HTTP请求者进行的GUI,例如这个,它就像在下面做一个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://www.mywebsite.com:port/Application?key=apikey&id=id&option=enable|disable

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

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?

推荐答案

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的回答帮助指出了我正确的方向。多一点挖掘帮助我找到了一个更优雅的解决方案,由这个答案引导。

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

这篇关于如何在Ruby中发送HTTP PUT请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆