检查 Ruby 中是否存在 URL [英] Check if URL exists in Ruby
本文介绍了检查 Ruby 中是否存在 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将如何使用 Ruby 检查 URL 是否存在?
How would I go about checking if a URL exists using Ruby?
例如,对于网址
https://google.com
结果应该是真实,但对于网址
the result should be truthy, but for the URLs
https://no.such.domain
或
https://stackoverflow.com/no/such/path
结果应该是falsey
推荐答案
使用 Net::HTTP 库.
require "net/http"
url = URI.parse("http://www.google.com/")
req = Net::HTTP.new(url.host, url.port)
res = req.request_head(url.path)
此时 res
是一个 Net::HTTPResponse 包含请求结果的对象.然后您可以检查响应代码:
At this point res
is a Net::HTTPResponse object containing the result of the request. You can then check the response code:
do_something_with_it(url) if res.code == "200"
注意:要检查基于 https
的 url,use_ssl
属性应为 true
为:
Note: To check for https
based url, use_ssl
attribute should be true
as:
require "net/http"
url = URI.parse("https://www.google.com/")
req = Net::HTTP.new(url.host, url.port)
req.use_ssl = true
res = req.request_head(url.path)
这篇关于检查 Ruby 中是否存在 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文