Ruby:检查URI是否为HTTPS?

Ruby:检查URI是否为HTTPS?,ruby,https,uri,Ruby,Https,Uri,我想检查URI是否需要SSL身份验证: url = URI.parse("http://www.google.com") # [some code] if url.instance_of? URI::HTTPS http.use_ssl=true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end 但是,这几行会引发以下错误 /usr/lib/ruby/1.8/uri/common.rb:436:in `split': bad UR

我想检查URI是否需要SSL身份验证:

url = URI.parse("http://www.google.com")

# [some code]

if url.instance_of? URI::HTTPS
   http.use_ssl=true
   http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
但是,这几行会引发以下错误

/usr/lib/ruby/1.8/uri/common.rb:436:in `split': bad URI(is not URI?): HTTPS (URI::InvalidURIError)
    from /usr/lib/ruby/1.8/uri/common.rb:485:in `parse'
    from /usr/lib/ruby/1.8/uri/common.rb:608:in `URI'
    from links.rb:18
为什么会发生这种情况?

>uri=uri.parse(“http://www.google.com")
>> uri = URI.parse("http://www.google.com")
=> #<URI::HTTP:0x1014ca458 URL:http://www.google.com>
>> uri.scheme
=> "http"
>> uri = URI.parse("https://mail.google.com")
=> #<URI::HTTPS:0x1014c2e60 URL:https://mail.google.com>
>> uri.scheme
=> "https"
=> # >>uri.scheme =>“http” >>uri=uri.parse(“https://mail.google.com") => # >>uri.scheme =>“https”

因此,您可以对照简单的“https”字符串检查uri的方案。

如前面的答案所示,
HTTP
https
是不同的类。 尤其是,
HTTPS
HTTP
类的一个子类。因此,您可以使用?的实例进行检查

http  = URI.parse "http://example.com"
https = URI.parse "https://example.com"

http.instance_of?  URI::HTTPS  #=> false
https.instance_of? URI::HTTPS  #=> true

但是,如果这个层次结构发生变化,那么代码可能会中断,因此上述答案可能更适合未来

改变类层次结构的概率与
scheme
方法IMHO基本相同。标准库仍然相当稳定
instance\u of?(URI::HTTPS)
可能是一个更好的选择,因为如果我键入一个字符串(比如
http.use\u ssl=(URI.scheme='htps')
),我就不会出错,而
instance\u of?(URI::htps)
给出了
未初始化常量,顺便说一下,解释了为什么
OpenSSL::ssl::VERIFY\u NONE
不是最佳选择