Ruby:检查 URI 是否为 HTTPS?

发布于 2024-08-20 20:49:36 字数 516 浏览 2 评论 0原文

我想检查 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

为什么会发生这种情况?

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:18

Why is it happening?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

自演自醉 2024-08-27 20:49:36
>> 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"

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

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

无妨# 2024-08-27 20:49:36

如上一个答案所示,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

但如果这个层次结构发生改变,那么你的代码可能会崩溃,因此上面的答案可能更适合未来。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文