Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send an HTTP PUT request in Ruby?

Tags:

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

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

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.

How can I replicate such a request in Ruby?

like image 818
finiteloop Avatar asked Jul 09 '12 21:07

finiteloop


People also ask

How do I send a HTTP PUT request?

Sending a PUT Request with Axios The simplest way to make the PUT call is to simply use the put() function of the axios instance, and supply the body of that request in the form of a JavaScript object: const res = await axios. put('/api/article/123', { title: 'Making PUT Requests with Axios', status: 'published' });

How do you create a post request in Ruby?

POST request with do block Using the object created in the do block we use the . body object method to add our params encoded using URI. There are other useful methods like request. headers['Content-Type'] = 'application/json' here setting the request's content type, or request.

Can you send body put request?

If the request has a Content-Length header, then it has a body. It may be an empty body, but still a body. In contrast to a request with no Content-Length header, which has no body at all, not even an empty one. So yes, a PUT request, technically, strictly, has to have a body.


1 Answers

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')
like image 163
Larry OBrien Avatar answered Sep 22 '22 13:09

Larry OBrien