HTTPS请求错误:未定义的方法`set_body_internal'

时间:2014-03-20 15:09:14

标签: ruby ssl https request

以下代码无法执行:

require 'net/http'

uri = URI('https://example.com:8443')
http = Net::HTTP.new(uri.host, uri.port)

# Enable SSL/TLS ?
if uri.scheme == "https"
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER
  http.ca_file = File.join(File.dirname(__FILE__), "ca-rsa-cert.pem")
end

http.start {
  http.request(uri)
}

错误是:

$ ./TestCert.rb
/usr/lib/ruby/1.9.1/net/http.rb:1292:in `request': undefined method `set_body_internal'
for #<URI::HTTPS:0x00000001a47fd0 URL:https://example.com:8443> (NoMethodError)
    from ./TestCert.rb:16:in `block in <main>'
    from /usr/lib/ruby/1.9.1/net/http.rb:745:in `start'
    from ./TestCert.rb:15:in `<main>'

Ruby NoMethodError (undefined method `set_body_internal') with HTTP get不同,我使用的是HTTPS而我并不关心响应。我只需要Ruby来建立连接以测试SSL / TLS服务器。

我确实尝试根据相关问题捕获响应,但是出现了相同的错误:

http.start {
  response = http.request uri
}

这也有同样的错误:

response = http.start {
  http.request uri
}

http.get也失败了(但错误不同 - undefined method 'empty?'):

response = http.start {
  http.get uri
}

另一次失败(但有不同的错误 - undefined method 'empty?'):

http.start {
  response = http.get uri
}

如果重要,这是一个运行Ruby 1.9.3p194的Debian 7.3(x64)系统。

如何使用Ruby通过SSL / TLS发出HTTP请求?

1 个答案:

答案 0 :(得分:3)

我认为您的通话http.request(uri)错误,您应该传递一种请求对象,例如Net::HTTP::Get而不是uri。请尝试使用以下代码:

require 'net/http'

uri = URI('https://example.com:8443')
http = Net::HTTP.new(uri.host, uri.port)

# Enable SSL/TLS ?
if uri.scheme == "https"
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER
  http.ca_file = File.join(File.dirname(__FILE__), "ca-rsa-cert.pem")
end

req = Net::HTTP::Get.new('/')
http.request(req)

或直接致电request_get('/')。该方法将为您创建Get对象,如文档说明:

def request_get(path, initheader = nil, &block) # :yield: +response+
  request(Get.new(path, initheader), &block)
end