通过Net :: HTTP在Ruby中发送http post请求

时间:2012-10-31 06:17:20

标签: ruby http http-headers

我正在向Web服务发送带有自定义标头的请求。

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

它没有用,我收到错误:

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

我该如何解决这个问题?

P.S。 Ruby 1.9.3

3 个答案:

答案 0 :(得分:12)

Net::HTTP#post的第二个参数需要是String,其中包含要发布的数据(通常是表单数据),标题将位于可选的第三个参数中。

答案 1 :(得分:8)

试试这个:

有关详细文档,请查看: 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

答案 2 :(得分:0)

正如qqx所提到的,Net::HTTP#post的第二个参数必须是String

幸运的是,有一个简洁的函数可以将哈希值转换为所需的字符串:

response = https.post(uri.path, URI.encode_www_form(headers))