开发者

Ruby: Checking if URI is HTTPS?

I would like to check if the URI will need SSL authentication:

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

However, those few lines throw the following error..

/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:1开发者_Python百科8

Why is it happening?


>> 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"

So you could check uri's scheme against simple "https" string.


as shown in the previous answer, HTTP and HTTPS are different classes. in particular, HTTPS is a subclass of the HTTP class. thus you could check with 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

but if this hierarchy ever gets changed, then your code could break, thus the above answer might be more future-proof.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜