Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

GET URL httpbin

  • get_response
  • URI
  • Net::HTTP
  • HTTPSuccess

Let's start with a really simple example:

This is a plain GET requests

require 'net/http'

url = 'https://httpbin.org/get'
uri = URI(url)
# puts(uri)

response = Net::HTTP.get_response(uri)
# puts response.class  # Net::HTTPOK
if response.is_a?(Net::HTTPSuccess)
    #puts "Headers:"
    #puts response.to_hash.inspect
    #puts '------'
    puts response.body
else
    puts response.code
end

The get_response method of the Net::HTTP class.

The response that we stored in a variable cleverly named response can be interrogated to see if the response was a success or failure. It is an instance of a Net::HTTPResponse class. In case it is a success we print the body of the response and see this:

{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip;q=1.0,deflate;q=0.6,identity;q=0.3",
    "Host": "httpbin.org",
    "User-Agent": "Ruby",
    "X-Amzn-Trace-Id": "Root=1-6381d91a-6f521a3c0fa5af313924005b"
  },
  "origin": "46.120.8.206",
  "url": "https://httpbin.org/get"
}

For the other case see the next example.