2010-02-06 71 views
13

我想檢查URI需要SSL認證:Ruby:檢查URI是否是HTTPS?

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 

爲什麼會發生?

+0

順便說一句,https://mislav.net/2013/07/ruby-openssl/解釋了爲什麼'OpenSSL :: SSL :: VERIFY_NONE'不是最佳選擇 – 2018-01-27 14:34:15

回答

20
>> 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的方案對簡單的「https」字符串。

8

如前面的答案所示,HTTPHTTPS是不同的類。 特別是,HTTPSHTTP類的一個子類。因此您可以使用instance_of?進行檢查。

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

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

但是如果這個層次結構發生了變化,那麼你的代碼可能會中斷,因此上述答案可能會更具前瞻性。

+0

更改類層次結構的概率基本相同與'scheme'方法一樣,恕我直言。標準庫仍然相當穩定。 ''instance_of?(URI :: HTTPS)''可以是一個更好的選擇,因爲如果我錯誤地輸入了一個字符串(比如'http.use_ssl =(uri.scheme =='htps')'),我就沒有錯誤,而'instance_of? (URI :: HTPS)'給出'未初始化的常量' – 2018-01-27 14:31:20