我如何使用Ruby判断URL是否存在?
例如,对于URL
https://google.com
结果应该是truthy,但对于URL
https://no.such.domain
或
https://stackoverflow.com/no/such/path
结果应该是falsey
我如何使用Ruby判断URL是否存在?
例如,对于URL
https://google.com
结果应该是truthy,但对于URL
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对象.然后,您可以判断响应代码:
do_something_with_it(url) if res.code == "200"
Note:要判断基于https
的url,use_ssl
属性应为true
,如下所示:
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)