Net::HTTP in depth
A GET and its status
Net::HTTP is in the standard library, so a request needs no gem. The shortest form takes a URI and returns a response object whose code decides what happened:
ruby -e 'require "net/http"; puts Net::HTTP.get_response(URI("https://example.com/")).code'
200
The one-liner is fine for a health check. It has no timeout that a caller can set, no retry and no way to reuse the connection, which is why the next section opens the connection by hand.
Timeouts, headers and SSL
A client that can hang is not a client. open_timeout bounds the connect, read_timeout bounds each read, and use_ssl is what makes an https URI work:
require "net/http" uri = URI("https://example.com/") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.open_timeout = 5 http.read_timeout = 5 res = http.get(uri.path) p res.code p res["content-type"] p res.body.bytesize p res.is_a?(Net::HTTPSuccess)
ruby http_get.rb
"200" "text/html; charset=utf-8" 577 true
res[...] reads a response header; Net::HTTPSuccess is the class for a 2xx, so the check does not compare strings. A request that sends headers passes them as a hash, and a header key is written the way the API expects it.
Redirects
Net::HTTP does not follow a redirect by default. A 3xx is a response with the next URL in the location header, and following it is a decision the client makes:
ruby -e 'require "net/http"; res = Net::HTTP.get_response(URI("https://httpbin.org/redirect/1")); p res.code; p res["location"]'
"302" "/get"
Following is a loop with a limit: resolve the location against the original URI, count the hops, refuse after five, and drop the body before the next request. A redirect that changes the host is also where a credential would leak, so a client that carries an authorization header does not follow one.
A POST
A body and a content type are the two extra arguments. The response is read the same way as a GET, and for JSON the body is parsed after the status check:
ruby -e 'require "net/http"; require "json"; uri = URI("https://httpbin.org/post"); res = Net::HTTP.post(uri, "name=Ada", "Content-Type" => "application/x-www-form-urlencoded"); p res.code; p JSON.parse(res.body)["form"]'
"200" {"name" => "Ada"}
Net::HTTP.post opens and closes the connection for one request. A series of requests to one host is faster through Net::HTTP.start with a block, which keeps the connection open for the whole block.
What to watch for
A 4xx is not an exception in Net::HTTP; it is a response. Check
res.is_a?(Net::HTTPSuccess) before parsing the
body, or a JSON parse error replaces the useful "401 unauthorized".
A read timeout applies to one read, not to the whole response. A slow
server can stream forever under it, so a client with a total budget also
checks the clock between chunks.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does this program print?
require "net/http" uri = URI("https://example.com/hello?x=1") puts uri.path puts uri.queryAnswer
/hello / x=1
path is the part after the host and query is the part after the question mark, without the mark.
-
What does this program print?
require "net/http" uri = URI("https://example.com/hello?x=1") res = Net::HTTPResponse::CODE_TO_OBJ["200"].new("1.1", "200", "OK") p res.codeAnswer
"200"
A response code is a string, and p shows it with quotes.
-
What does this program print?
require "net/http" req = Net::HTTP::Post.new("/post") req.body = "name=Ada" req["Content-Type"] = "application/x-www-form-urlencoded" puts req.body puts req["Content-Type"]Answer
name=Ada / application/x-www-form-urlencoded
The body and the content type are stored on the request object exactly as they were set.
-
What does
Net::HTTP.get_responsereturn?Answer
A response object with the code, the headers and the body
The whole response is read before the object is returned, so code, headers and body are all available.
-
What does
read_timeoutbound?Answer
Each read after the connection is open
It applies to one read, which is why a client with a total budget checks the clock as well.
-
What does this program print?
require "net/http" puts Net::HTTPResponse::CODE_TO_OBJ["200"] < Net::HTTPSuccessAnswer
true
A 2xx response is a Net::HTTPSuccess, so the class test holds without comparing code strings.
-
Where does a redirect put the address of the next page?
Answer
In the location header
A 3xx response carries the next URL in location, and following it is a decision the client makes.
-
Why does a client that carries an authorization header not follow a redirect to another host?
Answer
The credential would be sent to a host that did not receive it before
A host change is where a token would leak, which is why the client refuses that hop.
-
What does this program print?
require "uri" base = URI("https://example.com/a/b") next_uri = URI.join(base, "/get") puts next_uriAnswer
https://example.com/get
A location that starts with a slash replaces the whole path, which is how a redirect is resolved.
-
Why is
Net::HTTP.start(host, port) { |http| ... }useful for several requests?Answer
It keeps one connection open for the whole block
The block form opens the connection once, so a series of requests to one host does not reconnect each time.
Article author: Arthur Isaev