tags:

views:

451

answers:

1

I am trying to write a script to check if a given URL exists and return itself, if it exists. The file types will be .jpg and .mov.

I am currently using the open-uri std library but I'm pretty sure I should be using something else.

begin
    if (open(image_url).read)
        puts image_url
    end
    if (open(video_url).read)
        puts video_url
    end
  rescue
end

As you can see this is pretty inefficient because it reads the entire file. Any other solutions?

+3  A: 

You could use an HTTP library like the standard library 'net/http' or something else like the cURB bindings, but essentially you just want to issue an HTTP HEAD request which just gives you the header information and not the actual response body. If the HEAD request succeeds you get an HTTP 200 if it doesnt exist you get an HTTP 404 (you could get other responses such as internal error (HTTP 500) and what you decide to do with those, well its up to you).

Long story short, use HTTP HEAD.

Cody Caughlan
You do find a few servers which don't respond well to HTTP HEAD though, so it's not 100%.
Matthew Wilson
Thanks!@matthew True it isn't 100% but the server's I'm trying to query work well.
puttputt