Search code examples
rubynet-http

Check Ruby HTTP response for success


How does one properly check the response from Net::HTTP::Get (for example) for "success" (i.e., a 2xx return code)? The documentation seems to be sadly silent on this simple question.

I have:

response=Net::HTTP.new( host, port ).request my_get_request # details not important

After a bunch of Googling and near-random typing, I finally determined that this works:

response.class < Net::HTTPSuccess

Is that actually the canonical way to do it?


Solution

  • For Net::HTTP, yes, checking the class of the response object is the way to do it. Using kind_of? (aliased also as is_a?) is a bit clearer (but functionally equivalent to using <):

    response.kind_of? Net::HTTPSuccess
    

    Calling value on response will also raise a Net::HTTPError if the status code was not a successful one (what a poorly named method…).

    If you can, you may want to consider using a gem instead of Net::HTTP, as they often offer better APIs and performance. Typhoeus and HTTParty are two good ones, among others.