[Ruby] 檢查URL存在與否
require "net/http"
def remote_file_exists?(url)
url = URI.parse(url)
Net::HTTP.start(url.host, url.port) do |http|
puts http.head(url.request_uri).code == "200"
return http.head(url.request_uri).code == "200"
end
end
或
```rb require "net/http" def url_exist?(url_string)
url = URI.parse(url_string)
req = Net::HTTP.new(url.host, url.port)
req.use_ssl = (url.scheme == 'https')
path = url.path if url.path.present?
res = req.request_head(path || '/')
puts res.code != "404" # false if returns 404 - not found rescue Errno::ENOENT
puts false # false if can't find the server end ```
留言