2

In a Rails app, I'd like to make a HTTP HEAD request for a resource (a user-provided URL), to make sure that it exists. I'd also like a timeout, to ensure that the method fails after spending a reasonable period of time waiting. What is the most straightforward way to accomplish this (using the standard library, if possible)?

jrdioko
  • 32,230
  • 28
  • 81
  • 120

1 Answers1

11

Try this snippet:

require 'net/http'

Net::HTTP.start('www.some_site.com') do |http|
  http.open_timeout = 2
  http.read_timeout = 2
  req = Net::HTTP::Head.new('/')
  http.request(req).each { |k, v| puts "#{k}: #{v}" }
end

Hope this is what you're looking for.

UPDATE

Because there is head method that looks like

def head(path, initheader = nil)
  request(Head.new(path, initheader))
end

You can also use this snippet:

require 'net/http'

Net::HTTP.start('www.rubyinside.com') do |http|
  http.open_timeout = 2
  http.read_timeout = 2
  http.head('/').each { |k, v| puts "#{k}: #{v}" }
end
WarHog
  • 8,622
  • 2
  • 29
  • 23
  • Thanks. Should `Net::HTTP::Head.new('/')` be `http.head('/')`? ([doc](http://apidock.com/ruby/Net/HTTP/head)) – jrdioko Nov 04 '11 at 21:43
  • 1
    Feel free to use any method - `http.head()` is the abbreviation for request creation and send them to the server. I've updated my initial post for clearness – WarHog Nov 04 '11 at 21:56
  • @WarHog are you sure that the `http.open_timeout` does anything at all? I am under the impression that it is only used for opening the connection, and that is done by `Net::HTTP.start` I believe. – Rodrigue Oct 25 '12 at 15:56