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
Article author: Arthur Isaev