Sending http post request in Ruby by Net::HTTP

2020-06-07 05:30发布

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

3条回答
太酷不给撩
2楼-- · 2020-06-07 05:52

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))
查看更多
该账号已被封号
3楼-- · 2020-06-07 06:08

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.

查看更多
不美不萌又怎样
4楼-- · 2020-06-07 06:08

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
查看更多
登录 后发表回答