2012-10-31 190 views
19

我正在向Web服務發送帶自定義標頭的請求。通過Net :: HTTP發送Ruby中的http發佈請求

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

回答

12

Net::HTTP#post的第二個參數需要是String,其中包含要發佈的數據(通常是表單數據),這些標題將位於可選的第三個參數中。

+9

那麼,這裏的工作代碼是什麼? – rh4games

7

試試這個:

有關詳細的文檔,看看這個: 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 
+0

如何使用此功能發佈json主體?> –

+1

'data = {「aaa」=>「111」} .to_json; request.body =「[#{data}]」' –

0

如前所述qqx的Net::HTTP#post需求的第二個參數是一個String

幸運的是,有將散列轉換爲所需字符串的整潔函數:

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