HTTP clients

Net::HTTP GET

Net::HTTP lives in the standard library, so a GET request needs only a require and a URI.

The get_response method returns a response object with the status code and the body.

require "net/http" uri = URI("https://example.com/") response = Net::HTTP.get_response(uri) puts response.code puts response.body[0, 100]

POST JSON

Posting JSON means generating a JSON string and passing it with a content type header.

The Net::HTTP.post shortcut takes the URI, the body string, and a header hash.

require "net/http" require "json" uri = URI("https://example.com/users") body = JSON.generate({ "name" => "Ada", "role" => "admin" }) response = Net::HTTP.post(uri, body, { "Content-Type" => "application/json" }) puts response.code puts response.body

Timeouts

Network calls can hang, so set an open timeout for connecting and a read timeout for waiting on data.

Both values live on the Net::HTTP object and apply before the request runs.

require "net/http" uri = URI("https://example.com/") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = (uri.scheme == "https") http.open_timeout = 5 http.read_timeout = 10 response = http.get("/") puts response.code

Handle failures

Name resolution failures and slow servers raise exceptions, so wrap requests in begin and rescue.

Rescue SocketError for DNS problems and the Net timeout classes for slow responses.

require "net/http" begin response = Net::HTTP.get_response(URI("https://example.com/")) puts response.code rescue SocketError => e puts "DNS failed: #{e.message}" rescue Net::OpenTimeout, Net::ReadTimeout puts "Timed out" end

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does this program print? require "uri" uri = URI("https://example.com/users?page=2") puts uri.host puts uri.query

    Answer

    example.com / page=2

    URI splits the scheme, the host, the path and the query, and host and query are the parts asked for.

  2. What does this program print? require "json" body = JSON.generate({ "name" => "Ada", "role" => "admin" }) puts body

    Answer

    {"name":"Ada","role":"admin"}

    generate writes compact JSON, and puts prints the string itself rather than its inspect form.

  3. What does Net::HTTP.get_response(URI("https://example.com/")) return?

    Answer

    A response object with the status code and the body

    The shortcut sends the request and hands back the response, whose code and body are then read.

  4. Which timeout covers the wait to establish the connection?

    Answer

    open_timeout

    open_timeout covers connecting, and read_timeout covers waiting for data after that.

  5. What does this program print? require "socket" begin raise SocketError, "getaddrinfo: Name or service not known" rescue SocketError => e puts "DNS failed: #{e.message}" end

    Answer

    DNS failed: getaddrinfo: Name or service not known

    The rescue catches the raised error and interpolates its message into the printed line.

  6. Where are use_ssl and the timeouts set on a Net::HTTP object?

    Answer

    On the Net::HTTP object before the request runs

    The connection settings belong to the HTTP object, which is why the block builds one with Net::HTTP.new.

  7. Which exception does a name that does not resolve raise?

    Answer

    SocketError

    A failed lookup is a socket error, and the rescue that names SocketError is the one for it.

  8. What does Net::HTTP.get_response do when the server answers 404?

    Answer

    Returns a response whose code is "404", so the caller checks it

    An HTTP error status is a response, not an exception; only transport failures raise.

  9. Which header does a JSON POST need?

    Answer

    Content-Type: application/json

    The content type tells the server that the body is JSON rather than a form or plain text.

  10. Why does the timeout example build Net::HTTP.new instead of calling Net::HTTP.get_response?

    Answer

    The shortcut has no way to pass the timeouts

    The instance is what carries open_timeout and read_timeout before the request runs.

Article author: Arthur Isaev