23

我正在向 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)

我该如何解决这个问题?

附言Ruby 1.9.3

4

3 回答 3

13

试试这个:

有关详细文档,请查看: 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
于 2012-10-31T07:31:34.467 回答
12

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

于 2012-10-31T06:27:37.430 回答
0

正如 qqx 提到的,第二个参数Net::HTTP#post需要是String

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

response = https.post(uri.path, URI.encode_www_form(headers))
于 2014-07-29T10:36:41.353 回答