SRobertJames SRobertJames - 1 year ago 105
Ruby Question

Setting an HTTP Timeout in Ruby 1.9.3

I'm using Ruby 1.9.3 and need to GET a URL. I have this working with

, however, if the site is down,
ends up hanging.

While searching the internet, I've seen many people faced similar problems, all with hacky solutions. However, many of those posts are quite old.


  • I'd prefer using
    to installing a new gem.

  • I need both the Body and the Response Code. (e.g. 200)

  • I do not want to
    require open-uri
    , since that makes global changes and raises some security issues.

  • I need to GET a URL within X seconds, or return error.

Using Ruby 1.9.3, how can I GET a URL while setting a timeout?

To clarify, my existing code looks like:


Trying to add:


Results in:

NoMethodError: undefined method `open_timeout' for Net::HTTP:Class

Max Max
Answer Source

You can set the open_timeout attribute of the Net::HTTP object before making the connection.

uri = URI.parse(url), uri.port) do |http|
  http.open_timeout = 1000
  response = http.request_get(uri.request_uri)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download