Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending http post request in Ruby by Net::HTTP

Tags:

I'm sending a request with custom headers to a web service.

require 'uri' require 'net/http'  uri = URI("https://api.site.com/api.dll") https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true headers =  {     'HEADER1' => "VALUE1",     'HEADER2' => "HEADER2" }  response = https.post(uri.path, headers)  puts response 

It's not working, I'm receiving an error of:

/usr/lib/ruby/1.9.1/net/http.rb:1932:in `send_request_with_body': undefined method `bytesize' for #<Hash:0x00000001b93a10> (NoMethodError) 

How do I solve this?

P.S. Ruby 1.9.3

like image 956
Alan Coromano Avatar asked Oct 31 '12 06:10

Alan Coromano


People also ask

How do you create a post request in Ruby?

POST request For this request we use the post_form method of Net::HTTP , and after the uri we give our params in the key value form. Then we print the response body if the request was a success. Of course do not hesitate to dive in the docs, and here is a cheat sheet for quick reference.

What is Net HTTP?

Net::HTTP provides a rich library which can be used to build HTTP user-agents. For more details about HTTP see [RFC2616](www.ietf.org/rfc/rfc2616.txt). Net::HTTP is designed to work closely with URI.


2 Answers

Try this:

For detailed documentation, take a look at: http://www.rubyinside.com/nethttp-cheat-sheet-2940.html

require 'uri' require 'net/http'  uri = URI('https://api.site.com/api.dll') https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true  request = Net::HTTP::Post.new(uri.path)  request['HEADER1'] = 'VALUE1' request['HEADER2'] = 'VALUE2'  response = https.request(request) puts response 
like image 155
Arun Kumar Arjunan Avatar answered Oct 09 '22 17:10

Arun Kumar Arjunan


The second argument of Net::HTTP#post needs to be a String containing the data to post (often form data), the headers would be in the optional third argument.

like image 28
qqx Avatar answered Oct 09 '22 18:10

qqx