26

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

Alan Coromano
  • 24,958
  • 53
  • 135
  • 205

3 Answers3

15

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
Matilda Smeds
  • 1,384
  • 11
  • 18
Arun Kumar Arjunan
  • 6,827
  • 32
  • 35
14

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.

qqx
  • 18,947
  • 4
  • 64
  • 68
2

As qqx mentioned, the second argument of Net::HTTP#post needs to be a String

Luckily there's a neat function that converts a hash into the required string:

response = https.post(uri.path, URI.encode_www_form(headers))
davegson
  • 8,205
  • 4
  • 51
  • 71
  • Form data and headers are completely different. Yes, you can convert the Hash of headers to form data, but this likely won't give the expected results. If `headers` actually contains data that should be sent as form contents, I'd say that's a very badly named variable and should be renamed. – qqx Aug 21 '19 at 20:28