Skip to content
David Cook edited this page Sep 20, 2022 · 15 revisions

When we make an HTTP request, we obtain an HTTP::Response object:

>> response = HTTP.get('https://www.google.com')
=> #<HTTP/1.0 200 OK @headers={"Content-Type"=>"text/html; charset=UTF-8", "Date"=>"Fri, ...>

There are several methods of interest we can call on the response (see also the YARD documentation):

  • #body: (returns HTTP::Response::Body) an object representing the body. Can be used for streaming
  • #code: (returns Fixnum) the HTTP status code of the response
  • #status: (returns HTTP::Response::Status) an object representing the status of the response
  • #content_type: (returns HTTP::ContentType) the content type of the response
  • #cookies: (returns HTTP::CookieJar) a cookie jar containing all of the response cookies for a request
  • #flush: (returns self) reads and discards the response body. Useful for persistent connections
  • #parse: (return value depends on MIME type) parse the body using a parser defined for the #content_type
  • #to_s: (returns String) quickly obtain the response body as a string

Body

We can read the response body into a string by calling #to_s:

>> response.body.to_s
=> "<!doctype html>..."

We can also stream it with #each:

>> response.body.each { |chunk| ... }

or with #readpartial:

>> response.body.readpartial
=> "...first chunk..."
>> response.body.readpartial
=> "...next chunk..."

Status

response.status.informational? # 1xx
response.status.success? # 2XX
response.status.redirect? # 3xx
response.status.client_error? # 4XX
response.status.server_error? # 5XX
response.status #=> eg 500
response.status.reason #=> eg "Internal Server Error"
response.status.to_s #=> eg "500 Internal Server Error"