Reputation: 10067
I need to write code which will determine if a file exists by checking its URL.
Currently I implement this:
error_code = 400;
response = Net::HTTP.get_response(URI(url));
return response.code.to_i < error_code;
But, it's not working right because each time it downloads the file, which is really slow if I have big files or a lot of them.
How do I determine if a file exists on the remote side without downloading it?
Upvotes: 22
Views: 12254
Reputation: 7530
If you want to use Rubys included Net::HTTP
then you can do it this way:
uri = URI(url)
request = Net::HTTP.new uri.host
response= request.request_head uri.path
return response.code.to_i == 200
Upvotes: 33
Reputation: 644
With the rest-client
gem installed, do something like this
require "rest-client"
begin
exists = RestClient.head("http://google.com").code == 200
rescue RestClient::Exception => error
exists = (error.http_code != 404)
end
Then "exists" is a boolean depending whether if it exists or not. This will only get the header information, not the file, so it should be the same for small or big files.
Upvotes: 6
Reputation: 160551
I'd write it this way:
require 'net/http'
ERROR_CODE = 400
response = Net::HTTP.start('www.example.net', 80) do |http|
http.request_head('/index.html')
end
puts response.code.to_i < ERROR_CODE
Which outputs true
because I got a 302
for the response.code
.
Upvotes: 2