Ruby HTTP POST - Errors

2019-08-10 01:28发布

问题:

Can someone explain to me why I am getting this error when doing this POST? I pulled the snippet from the Ruby-docs page.

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

Perhaps I am missing a require or something?

require 'net/http'

uri= URI('http://ws.mywebservice.com/ws.php')
req = Net::HTTP::Post.new(uri.path)
req.set_form_data('xmlPayload' => '<TestRequest><Message>Hi Test</Message></TestRequest>')

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:

If you're using a version of Ruby prior to 1.9.3, you should use uri.host.

URI#hostname was added in Ruby 1.9.3. It is different than URI#host in that it removes brackets from IPv6 hostnames. For non-IPv6 hostnames it should behave identically.

The implementation (from APIdock):

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


标签: ruby http post