如何使用最新版本的 Ruby 连接到带有无效证书的 https 服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7969688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to connect to an https server with an invalid certificate using the latest versions of Ruby
提问by Jonathan
Consider the following code:
考虑以下代码:
require 'net/https'
uri = URI.parse("https://host/index.html")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.path)
response = http.request(request)
where https://host/index.htmlis a valid address with an invalid certificate on the server.
其中https://host/index.html是服务器上具有无效证书的有效地址。
On older versions of ruby (specifically 1.8.7-p334 and 1.9.2-p180) this code works fine. On all recent versions (1.8.7-p352, 1.9.2-p290 and 1.9.3-p0) it throws the following exception:
在旧版本的 ruby(特别是 1.8.7-p334 和 1.9.2-p180)上,这段代码工作正常。在所有最新版本(1.8.7-p352、1.9.2-p290 和 1.9.3-p0)上,它抛出以下异常:
OpenSSL::SSL::SSLError: SSL_connect SYSCALL returned=5 errno=0 state=unknown state
on the last line.
在最后一行。
Changing verify_mode to OpenSSL::SSL::VERIFY_PEERgives exactly the error suggesting it is attempting to verify the certificate in spite of the setting.
将 verify_mode 更改OpenSSL::SSL::VERIFY_PEER为准确地给出了错误,表明它尽管设置了但仍尝试验证证书。
How can I convince ruby to ignore the invalid certificate and connect?
如何说服 ruby 忽略无效证书并进行连接?
回答by tosterr
uri = URI("https://host/index.html")
req = Net::HTTP::Get.new(uri.path)
res = Net::HTTP.start(
uri.host, uri.port,
:use_ssl => uri.scheme == 'https',
:verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https|
https.request(req)
end
回答by Christoph Trautwein
require 'nokogiri'
require 'open-uri'
require 'net/https'
@doc = Nokogiri::HTML(open(my_url, :ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE))

