Our examples so far have assumed that you’re using valid URLs and are accessing documents that actually exist. However, Net::HTTP will return different responses based on whether the request is a success or not or if the client is being redirected to a different URL, and you can check for these. In the following example, a method called get_web_document is created that accepts a single URL as a parameter. It parses the URL, attempts to get the required document, and then subjects the response to a case/when block:

require 'net/http'
def get_web_document(url)
  uri = URI.parse(url)
  response = Net::HTTP.get_response(uri)
  case response
    when Net::HTTPSuccess:
      return response.body
    when Net::HTTPRedirection:
      return get_web_document(response['Location'])
    else
      return nil
  end
end

Call the defined method

puts get_web_document('http://www.rubyinside.com/test.txt')
puts get_web_document('http://www.rubyinside.com/non-existent')
Advertisements