Reputation: 5705
With curl
, I do the following to check if a webpage is online:
if curl --output /dev/null --silent --head --fail "${url}"; then
echo "URL exists: ${url}"
else
echo "URL does not exist: ${url}"
fi
However, if the server refuses HEAD
requests (or I don’t know), an alternative is to request only the first byte of the file:
if curl --output /dev/null --silent --fail --range 0-0 "${url}"; then
echo "URL exists: ${url}"
else
echo "URL does not exist: ${url}"
fi
The first case is easy to replicate in Ruby:
require 'net/http'
require 'uri'
uri = URI.parse(url)
response = Net::HTTP.get_response(uri)
if response.kind_of? Net::HTTPOK
puts "URL exists: #{url}"
else
puts "URL does not exist: #{url}"
end
How do I replicate the second curl
case?
Upvotes: 1
Views: 175
Reputation: 34328
The range option essentially only sets the Range
header. So to replicate you would do the same:
url = URI.parse(...)
req = Net::HTTP::Get.new(url.request_uri)
req['Range'] = 'bytes=0-0'
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = (url.scheme == "https")
response = http.request(req)
Upvotes: 2