HTTP client
suggest changeRuby ships with Net::HTTP, a complete HTTP/1.1 client, so most programs can talk HTTP without installing any gems. open-uri builds a simpler interface on top of it. For extra features (HTTP/2, concurrent requests, middleware) there are gems such as http (http.rb), httpx and Faraday.
This article covers the client side in depth: making requests, query strings and bodies, status codes, persistent connections, timeouts, redirects, streaming downloads, compression, authentication and HTTPS. Related topics have their own articles: HTTP headers, REST APIs (a JSON API client with retries and pagination, plus Faraday and HTTParty), File uploads and Cookies.
The examples were run with Ruby 4.0 (net-http 0.9, open-uri 0.5), http 6.0, httpx 1.9 and webrick 1.9.
A local server to experiment with
To get stable output, every example talks to a small WEBrick server running on your machine instead of a public website. webrick is no longer part of Ruby, so install it first with gem install webrick:
# server.rb - a tiny local server to try the examples against
require 'webrick'
require 'json'
require 'zlib'
server = WEBrick::HTTPServer.new(
Port: 8000,
Logger: WEBrick::Log.new(File::NULL),
AccessLog: []
)
# GET /hello -> plain text
server.mount_proc('/hello') do |_req, res|
res['Content-Type'] = 'text/plain; charset=utf-8'
res.body = "Hello, world!\n"
end
# Any method on /echo -> describes the request as JSON
class Echo < WEBrick::HTTPServlet::AbstractServlet
HEADERS = %w[user-agent accept content-type authorization x-request-id].freeze
def service(req, res) # handles every HTTP method
res['Content-Type'] = 'application/json'
res.body = JSON.generate(
method: req.request_method,
path: req.path,
query: req.query_string,
headers: HEADERS.to_h { [_1, req[_1]] }.compact,
body: req.body
)
end
end
server.mount('/echo', Echo)
# GET /port -> the client's TCP port (shows whether a connection was reused)
server.mount_proc('/port') do |req, res|
res.body = req.peeraddr[1].to_s
end
# GET /status/404 -> responds with that status code
server.mount_proc('/status') do |req, res|
res.status = req.path.split('/').last.to_i
res['Content-Type'] = 'text/plain'
res.body = "status #{res.status}\n"
end
# GET /redirect/3 -> 302 to /redirect/2 -> ... -> /hello
server.mount_proc('/redirect') do |req, res|
n = req.path.split('/').last.to_i
res.status = 302
res['Location'] = n > 1 ? "/redirect/#{n - 1}" : '/hello'
end
# GET /slow?seconds=3 -> waits before answering
server.mount_proc('/slow') do |req, res|
sleep req.query.fetch('seconds', '2').to_f
res.body = "finally\n"
end
# GET /bytes?n=1000000 -> n bytes of data, gzipped if the client accepts it
server.mount_proc('/bytes') do |req, res|
data = 'abcdefghij' * (req.query.fetch('n', '1000').to_i / 10)
if req['accept-encoding'].to_s.include?('gzip')
res['Content-Encoding'] = 'gzip'
data = Zlib.gzip(data)
end
res['Content-Type'] = 'application/octet-stream'
res.body = data
end
# GET /private -> requires HTTP Basic auth alice:secret
server.mount_proc('/private') do |req, res|
WEBrick::HTTPAuth.basic_auth(req, res, 'demo') do |user, pass|
user == 'alice' && pass == 'secret'
end
res.body = "Welcome, alice\n"
end
trap('INT') { server.shutdown }
puts 'Listening on http://localhost:8000'
server.start
Run it with ruby server.rb in one terminal and run the examples in another. Press Ctrl+C to stop it.
Simple GET requests
Net::HTTP.get returns the body as a String. Net::HTTP.get_response returns the whole response object:
require 'net/http'
# Body only, as a String
puts Net::HTTP.get(URI('http://localhost:8000/hello'))
# The full response
res = Net::HTTP.get_response(URI('http://localhost:8000/hello'))
p res
puts res.code # String, not Integer
puts res.message
puts res['Content-Type']
p res.body
Hello, world!
#<Net::HTTPOK 200 OK readbody=true>
200
OK
text/plain; charset=utf-8
"Hello, world!\n"
Note that res.code is a String ("200"). Use res.code.to_i when you need a number.
Net::HTTP.get returns the body no matter what the status is. A 404 page or a 500 error page comes back as if it were the content you asked for, so for anything beyond quick scripts use get_response and check the status.
Checking the status
Every status code has its own response class (Net::HTTPOK, Net::HTTPNotFound, ...), and the classes are grouped under Net::HTTPSuccess (2xx), Net::HTTPRedirection (3xx), Net::HTTPClientError (4xx) and Net::HTTPServerError (5xx). This makes case a natural fit:
require 'net/http'
%w[/hello /status/404 /status/500 /redirect/1].each do |path|
res = Net::HTTP.get_response(URI("http://localhost:8000#{path}"))
kind = case res
when Net::HTTPSuccess then 'success'
when Net::HTTPRedirection then "redirect to #{res['Location']}"
when Net::HTTPClientError then 'client error'
when Net::HTTPServerError then 'server error'
end
puts "#{path.ljust(12)} #{res.code} #{res.class.name.ljust(28)} #{kind}"
end
# value raises unless the response is 2xx
begin
Net::HTTP.get_response(URI('http://localhost:8000/status/404')).value
rescue Net::HTTPClientException => e
puts "#{e.class}: #{e.message}"
p e.response.code
end
/hello 200 Net::HTTPOK success
/status/404 404 Net::HTTPNotFound client error
/status/500 500 Net::HTTPInternalServerError server error
/redirect/1 302 Net::HTTPFound redirect to http://localhost:8000/hello
Net::HTTPClientException: 404 "Not Found"
"404"
Net::HTTP never raises on its own because of the status code. Either check the class or call res.value, which raises Net::HTTPClientException (4xx), Net::HTTPFatalError (5xx) or Net::HTTPRetriableError (3xx), each holding the response.
Query strings and request headers
Build query strings with URI.encode_www_form, which escapes values and repeats keys for Arrays. Never glue user input into a URL by hand (more on URI in Parsing URLs). Headers can be passed as a Hash:
require 'net/http'
require 'json'
uri = URI('http://localhost:8000/echo')
uri.query = URI.encode_www_form(q: 'ruby http', tags: %w[net web], page: 2)
puts uri
res = Net::HTTP.get_response(uri, { 'User-Agent' => 'demo/1.0', 'Accept' => 'application/json' })
data = JSON.parse(res.body)
puts data['query']
p data['headers']
p URI.decode_www_form(data['query'])
http://localhost:8000/echo?q=ruby+http&tags=net&tags=web&page=2
q=ruby+http&tags=net&tags=web&page=2
{"user-agent" => "demo/1.0", "accept" => "application/json"}
[["q", "ruby http"], ["tags", "net"], ["tags", "web"], ["page", "2"]]
POST and PUT with a body
Net::HTTP.post_form sends a form the way an HTML <form method="post"> does. Net::HTTP.post and Net::HTTP.put send any body you give them, so you set Content-Type yourself:
require 'net/http'
require 'json'
uri = URI('http://localhost:8000/echo')
# HTML-form style: application/x-www-form-urlencoded
res = Net::HTTP.post_form(uri, 'name' => 'Zoƫ', 'langs' => 'ruby & go')
data = JSON.parse(res.body)
puts data.values_at('method', 'body').inspect
puts data['headers']['content-type']
# JSON body
payload = JSON.generate(title: 'Dune', year: 1965)
res = Net::HTTP.post(uri, payload, 'Content-Type' => 'application/json')
data = JSON.parse(res.body)
puts data.values_at('method', 'body').inspect
# PUT works the same way
res = Net::HTTP.put(uri, payload, 'Content-Type' => 'application/json')
puts JSON.parse(res.body)['method']
["POST", "name=Zo%C3%AB&langs=ruby+%26+go"]
application/x-www-form-urlencoded
["POST", "{\"title\":\"Dune\",\"year\":1965}"]
PUT
For multipart/form-data (file uploads) see File uploads.
Request objects and persistent connections
The class methods above open a new TCP connection for every request and close it afterwards. Net::HTTP.start opens one connection, yields it, and closes it when the block ends. Inside the block you can use shortcut methods (get, head, post, ...) or build a request object for any HTTP method and send it with request:
require 'net/http'
require 'json'
Net::HTTP.start('localhost', 8000) do |http|
# Shortcut methods take a path
res = http.get('/echo')
p JSON.parse(res.body)['headers'] # the defaults Net::HTTP sends
# Request objects: Get, Head, Post, Put, Patch, Delete, Options
req = Net::HTTP::Patch.new('/echo?id=7')
req['Content-Type'] = 'application/json'
req['X-Request-Id'] = 'abc123'
req.body = '{"year":1966}'
res = http.request(req)
puts JSON.parse(res.body).values_at('method', 'query', 'body').inspect
res = http.request(Net::HTTP::Delete.new('/echo'))
puts JSON.parse(res.body)['method']
res = http.head('/hello')
p [res.code, res['Content-Length'], res.body]
end
{"user-agent" => "Ruby", "accept" => "*/*"}
["PATCH", "id=7", "{\"year\":1966}"]
DELETE
["200", "14", nil]
The default User-Agent is just Ruby. Some sites block that, so it's polite to send a descriptive one such as MyApp/1.2 (admin@example.com).
Reusing a connection saves a TCP handshake (and for HTTPS a TLS handshake) on every request, which is often the slowest part of a small request. The /port endpoint returns the client's port number, which shows how many connections were used:
require 'net/http'
uri = URI('http://localhost:8000/port')
# A new TCP connection for every call
ports = 5.times.map { Net::HTTP.get(uri) }
puts "separate calls: #{ports.uniq.size} connections"
# One connection, kept alive for all requests inside the block
ports = Net::HTTP.start(uri.host, uri.port) do |http|
5.times.map { http.get(uri.path).body }
end
puts "Net::HTTP.start: #{ports.uniq.size} connection"
separate calls: 5 connections
Net::HTTP.start: 1 connection
If the connection has to outlive a block (for example in a long-lived client object), call start without a block and finish when you are done. Net::HTTP reconnects by itself when the server has closed an idle connection. A Net::HTTP object is not thread-safe: give each thread its own.
Timeouts and network errors
The default timeouts are 60 seconds, which is far too long for most programs. Set them explicitly, either as setters or as options to Net::HTTP.start (open_timeout:, read_timeout:, write_timeout:):
require 'net/http'
uri = URI('http://localhost:8000/slow?seconds=3')
http = Net::HTTP.new(uri.host, uri.port)
p [http.open_timeout, http.read_timeout, http.write_timeout]
http.open_timeout = 2 # seconds to establish the connection
http.read_timeout = 1 # seconds to wait for each read
http.max_retries = 0 # don't retry idempotent requests after a timeout
t = Process.clock_gettime(Process::CLOCK_MONOTONIC)
begin
http.request_get(uri)
rescue Net::ReadTimeout => e
elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - t
puts "#{e.class} after #{elapsed.round(1)}s"
end
# Nothing listens on port 8999
begin
Net::HTTP.get(URI('http://localhost:8999/'))
rescue SystemCallError => e
puts e.class
end
# .invalid is a reserved top-level domain that never resolves
begin
Net::HTTP.get(URI('http://no-such-host.invalid/'))
rescue Socket::ResolutionError => e
puts e.class
end
[60, 60, 60]
Net::ReadTimeout after 1.0s
Errno::ECONNREFUSED
Socket::ResolutionError
Some things to know:
max_retriesdefaults to1: for idempotent requests (GET,HEAD,PUT,DELETE, ...) Net::HTTP quietly resends the request once after a read timeout or a dropped connection. With the default setting the example above would fail after 2 seconds, not 1.read_timeoutlimits each read, not the whole request. A server that trickles one byte every half second never triggers it. To cap the total time, wrap the call in your own deadline check or use a gem with a total request timeout (httpxhasrequest_timeout).- The errors to rescue for "the network failed" are
Net::OpenTimeout,Net::ReadTimeout,Net::WriteTimeout,SocketError(whichSocket::ResolutionErrorinherits from),SystemCallError(Errno::ECONNREFUSED,Errno::ECONNRESET, ...),EOFError,IOErrorand, for HTTPS,OpenSSL::SSL::SSLError.
The REST APIs article shows a client that turns these into its own exception classes and retries with backoff.
Following redirects
Net::HTTP does not follow redirects. A small loop handles them; resolve Location against the current URL because it may be relative, and limit the number of hops to avoid redirect loops:
require 'net/http'
def fetch(uri, limit: 5)
uri = URI(uri)
limit.times do
res = Net::HTTP.get_response(uri)
return res unless res.is_a?(Net::HTTPRedirection)
# Location may be relative ("/hello"), so resolve it against the current URL
uri = uri + res['Location']
puts " -> #{res.code} #{uri}"
end
raise "too many redirects (more than #{limit})"
end
res = fetch('http://localhost:8000/redirect/3')
puts "#{res.code} #{res.body}"
begin
fetch('http://localhost:8000/redirect/10')
rescue => e
puts e.message
end
-> 302 http://localhost:8000/redirect/2
-> 302 http://localhost:8000/redirect/1
-> 302 http://localhost:8000/hello
200 Hello, world!
-> 302 http://localhost:8000/redirect/9
-> 302 http://localhost:8000/redirect/8
-> 302 http://localhost:8000/redirect/7
-> 302 http://localhost:8000/redirect/6
-> 302 http://localhost:8000/redirect/5
too many redirects (more than 5)
This simple version always follows with GET, which is right for 301, 302 and 303. A 307 or 308 redirect asks the client to repeat the same method and body. Also think twice before sending an Authorization header on to a different host.
Streaming large downloads
res.body holds the whole body in memory. For large files pass a block to request (or request_get): the block receives the response before the body is read, and read_body with a block yields the body in chunks as they arrive:
require 'net/http'
uri = URI('http://localhost:8000/bytes?n=5000000')
Net::HTTP.start(uri.host, uri.port) do |http|
# Passing a block to request_get (or request) gives you the response
# before the body has been read
http.request_get(uri, 'Accept-Encoding' => 'identity') do |res|
total = res.content_length
done = 0
next_report = 25
File.open('download.bin', 'wb') do |f|
res.read_body do |chunk| # yields pieces as they arrive
f.write(chunk)
done += chunk.bytesize
while done * 100 >= total * next_report
puts "#{next_report}% (#{done} of #{total} bytes)"
next_report += 25
end
end
end
end
end
puts "saved #{File.size('download.bin')} bytes"
25% (1261376 of 5000000 bytes)
50% (2506560 of 5000000 bytes)
75% (3751744 of 5000000 bytes)
100% (5000000 of 5000000 bytes)
saved 5000000 bytes
Memory use stays small no matter how big the file is. content_length is nil when the server doesn't send Content-Length (e.g. a chunked response), so real code should handle that case. Check res.is_a?(Net::HTTPSuccess) before writing the file, too. This example asks for identity encoding so the progress numbers match the file size; see the next section.
Compression
Net::HTTP sends Accept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3 by default and transparently decompresses the body. It then removes the Content-Encoding header, so your code sees the response as if it had never been compressed. If you set Accept-Encoding yourself, automatic decoding is turned off and you get the raw bytes:
require 'net/http'
uri = URI('http://localhost:8000/bytes?n=100000')
Net::HTTP.start(uri.host, uri.port) do |http|
# Default: Net::HTTP asks for gzip and inflates the body for you
req = Net::HTTP::Get.new(uri)
p req['Accept-Encoding']
res = http.request(req)
p [res['Content-Encoding'], res.body.bytesize, res.decode_content]
# Setting Accept-Encoding yourself turns automatic decoding off
res = http.request(Net::HTTP::Get.new(uri, 'Accept-Encoding' => 'gzip'))
p [res['Content-Encoding'], res.body.bytesize, res.decode_content]
p Zlib.gunzip(res.body).bytesize
end
"gzip;q=1.0,deflate;q=0.6,identity;q=0.3"
[nil, 100000, true]
["gzip", 240, false]
100000
Authentication
basic_auth sets the Authorization header for HTTP Basic authentication. It is only Base64, not encryption, so use it over HTTPS only:
require 'net/http'
uri = URI('http://localhost:8000/private')
res = Net::HTTP.get_response(uri)
puts "#{res.code} #{res['WWW-Authenticate']}"
req = Net::HTTP::Get.new(uri)
req.basic_auth('alice', 'secret')
p req['Authorization']
res = Net::HTTP.start(uri.host, uri.port) { |http| http.request(req) }
puts "#{res.code} #{res.body}"
401 Basic realm="demo"
"Basic YWxpY2U6c2VjcmV0"
200 Welcome, alice
Token-based APIs use a header instead: req['Authorization'] = "Bearer #{ENV.fetch('API_TOKEN')}". Read secrets from the environment or a secrets store, never from source code.
HTTPS
For https:// URLs the class methods (get, get_response, post) turn on TLS automatically. With Net::HTTP.new or Net::HTTP.start pass use_ssl: true (or use_ssl: uri.scheme == 'https'). Certificates are verified against the system's trusted CAs by default.
To try this locally, this server creates a self-signed certificate for localhost and serves HTTPS on port 8443:
# tls_server.rb - HTTPS on port 8443 with a self-signed certificate
require 'webrick'
require 'webrick/https'
require 'openssl'
key = OpenSSL::PKey::EC.generate('prime256v1')
cert = OpenSSL::X509::Certificate.new
cert.version = 2
cert.serial = 1
cert.subject = cert.issuer = OpenSSL::X509::Name.parse('/CN=localhost')
cert.public_key = key
cert.not_before = Time.now
cert.not_after = Time.now + 24 * 60 * 60
ext = OpenSSL::X509::ExtensionFactory.new(cert, cert)
cert.add_extension(ext.create_extension('subjectAltName', 'DNS:localhost,IP:127.0.0.1'))
cert.add_extension(ext.create_extension('basicConstraints', 'CA:TRUE', true))
cert.sign(key, 'SHA256')
File.write('localhost.pem', cert.to_pem) # clients will trust this file
server = WEBrick::HTTPServer.new(
Port: 8443,
SSLEnable: true,
SSLCertificate: cert,
SSLPrivateKey: key,
Logger: WEBrick::Log.new(File::NULL),
AccessLog: []
)
server.mount_proc('/') { |_req, res| res.body = "secure hello\n" }
trap('INT') { server.shutdown }
server.start
A client refuses to talk to it until told to trust that certificate with ca_file: (or ca_path: / cert_store:):
require 'net/http'
uri = URI('https://localhost:8443/')
# The certificate isn't signed by a CA the system trusts, so verification fails
begin
Net::HTTP.get(uri)
rescue OpenSSL::SSL::SSLError => e
puts "#{e.class}: #{e.message}"
end
# Trust that one certificate explicitly
Net::HTTP.start(uri.host, uri.port, use_ssl: true,
ca_file: 'localhost.pem', min_version: :TLS1_2) do |http|
puts http.get('/').body
puts http.peer_cert.subject
end
OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 peeraddr=[::1]:8443 state=error: certificate verify failed (self-signed certificate)
secure hello
/CN=localhost
This is also how you talk to internal services that use a company CA. Avoid verify_mode: OpenSSL::SSL::VERIFY_NONE: it turns off the check that you are talking to the right server, so anyone on the network path can read and change the traffic. Client certificates (mutual TLS) are set with cert: and key:.
Concurrent requests with threads
Net::HTTP blocks while waiting for the network, but Ruby releases the global VM lock during I/O, so threads run requests in parallel just fine:
require 'net/http'
urls = 5.times.map { URI("http://localhost:8000/slow?seconds=1&n=#{_1}") }
start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
threads = urls.map do |uri|
Thread.new do
res = Net::HTTP.get_response(uri)
[uri.query, res.code]
end
end
results = threads.map(&:value) # waits for each thread, re-raises its exception
elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
results.each { |q, code| puts "#{code} #{q}" }
puts "5 requests in #{elapsed.round(1)}s"
200 seconds=1&n=0
200 seconds=1&n=1
200 seconds=1&n=2
200 seconds=1&n=3
200 seconds=1&n=4
5 requests in 1.0s
Five one-second requests finish in one second. For hundreds of URLs, don't start one thread per URL: use a fixed pool of workers that take URLs from a Queue, so you don't overload the server or run out of sockets.
open-uri
open-uri lets you read a URL like a file. It follows redirects and raises on HTTP errors, which makes it handy for scripts:
require 'open-uri'
require 'json'
# URI#open returns an IO-like object with response metadata attached
URI('http://localhost:8000/echo?x=1').open('User-Agent' => 'demo/1.0') do |f|
p f.status
p f.content_type
p JSON.parse(f.read)['headers']
end
# HTTP errors are raised as OpenURI::HTTPError
begin
URI('http://localhost:8000/status/404').read
rescue OpenURI::HTTPError => e
puts "#{e.message.strip} / #{e.io.read.strip}"
end
# Redirects are followed automatically
puts URI('http://localhost:8000/redirect/2').read
["200", "OK"]
"application/json"
{"user-agent" => "demo/1.0", "accept" => "*/*"}
404 Not Found / status 404
Hello, world!
Options such as open_timeout:, read_timeout: and http_basic_authentication: [user, pass] go into the same Hash as the headers. It only does GET. Always call open on a URI object (URI(url).open), never Kernel#open(url). Since Ruby 3.0 Kernel#open no longer opens URLs, and before Ruby 4.0 it ran a shell command when the string started with |, which was dangerous with untrusted input.
The http gem (http.rb)
gem install http gives a chainable API with JSON support, timeouts, redirects and persistent connections built in:
require 'http'
res = HTTP.headers('Accept' => 'application/json')
.timeout(connect: 2, read: 5)
.get('http://localhost:8000/echo', params: { q: 'ruby' })
p res.status.code
p res.content_type.mime_type
p res.parse['query'] # parse decodes JSON based on Content-Type
res = HTTP.post('http://localhost:8000/echo', json: { title: 'Dune' })
p res.parse.values_at('method', 'body')
res = HTTP.basic_auth(user: 'alice', pass: 'secret').get('http://localhost:8000/private')
p [res.code, res.to_s]
res = HTTP.follow(max_hops: 5).get('http://localhost:8000/redirect/3')
p [res.code, res.uri.to_s]
# A persistent connection to one host
HTTP.persistent('http://localhost:8000') do |http|
ports = 3.times.map { http.get('/port').to_s } # read the body before the next request
p ports.uniq.size
end
200
"application/json"
"q=ruby"
["POST", "{\"title\":\"Dune\"}"]
[200, "Welcome, alice\n"]
[200, "http://localhost:8000/hello"]
1
Each chained call (headers, timeout, basic_auth) returns a new client, so you can build a configured client once and reuse it.
HTTPX
gem install httpx gives a client that supports HTTP/2, sends several requests at once, and gets extra features from plugins:
require 'httpx'
res = HTTPX.get('http://localhost:8000/echo', params: { q: 'ruby' })
p res.status
p res.json['query']
# HTTP errors are returned, not raised; raise_for_status turns them into exceptions
res = HTTPX.get('http://localhost:8000/status/503')
p res.status
begin
res.raise_for_status
rescue HTTPX::HTTPError => e
puts "#{e.class}: status #{e.response.status}"
end
# Pass several URLs to get several responses, in the same order
responses = HTTPX.get('http://localhost:8000/hello', 'http://localhost:8000/port',
'http://localhost:8000/status/404')
p responses.map(&:status)
# Plugins add features: retries, redirects, auth, cookies, ...
http = HTTPX.plugin(:follow_redirects)
.plugin(:retries, max_retries: 2)
.with(timeout: { connect_timeout: 2, request_timeout: 10 })
p http.get('http://localhost:8000/redirect/2').uri.to_s
200
"q=ruby"
503
HTTPX::HTTPError: status 503
[200, 200, 404]
"http://localhost:8000/hello"
A network failure doesn't raise either: you get an HTTPX::ErrorResponse, and its error method returns the exception. When the server speaks HTTP/2, the requests in a multi-URL call are sent over one connection at the same time. Our WEBrick server only speaks HTTP/1.1, so HTTPX sends the requests to it one after another.
Which one to use
| Library | Good for |
|---|---|
Net::HTTP |
no dependencies, full control; scripts, gems, simple clients |
open-uri |
one-line GET of a URL in a script |
http (http.rb) |
a clean, chainable API on top of plain sockets |
httpx |
HTTP/2, many requests at once, plugins |
| Faraday | middleware stack, swappable backends; common in API wrapper gems (see REST APIs) |
Tips
- Always set timeouts. The 60-second defaults let one slow server hang a worker for minutes, especially with the automatic retry.
- Reuse connections when you make several requests to the same host (
Net::HTTP.startwith a block,HTTP.persistent, or a long-lived HTTPX session). - Check the status before using the body:
Net::HTTP, http.rb and HTTPX all return 4xx/5xx responses without raising. - Encode query strings with
URI.encode_www_formand JSON bodies withJSON.generate, never by string interpolation. - Stream large downloads with
read_bodyand a block instead of loading them into memory. - Never disable certificate verification; point
ca_file:at the right CA instead. - Don't log full URLs and headers if they can contain tokens, passwords or cookies.