Ruby HTTP POST – 错误

有人可以向我解释为什么我在这个POST时遇到这个错误? 我从Ruby-docs页面中提取了代码片段。

undefined method `hostname' for #URI::HTTP:0x10bd441d8 URL:http://ws.mittthetwitapp.com/ws.phpmywebservice (NoMethodError) 

也许我错过了一个要求或什么?

 require 'net/http' uri= URI('http://ws.mywebservice.com/ws.php') req = Net::HTTP::Post.new(uri.path) req.set_form_data('xmlPayload' => 'Hi Test') res = Net::HTTP.start(uri.hostname, uri.port) do |http| http.request(req) end case res when Net::HTTPSuccess, Net::HTTPRedirection # OK else res.value end 

如果您使用的是1.9.3之前的Ruby版本,则应使用uri.host

URI#hostname是在Ruby 1.9.3中添加的。 它与URI#host 不同之处在于它从IPv6主机名中删除括号。 对于非IPv6主机名,它的行为应该相同。

实现(来自APIdock ):

 def hostname v = self.host /\A\[(.*)\]\z/ =~ v ? $1 : v end