class Net::HTTPResponse - Documentation for Ruby 4.0 (original) (raw)

This class is the base class for Net::HTTP response classes.

About the Examples

Examples here assume that net/http has been required (which also requires uri):

require 'net/http'

Many code examples here use these example websites:

Some examples also assume these variables:

uri = URI('https://jsonplaceholder.typicode.com/') uri.freeze hostname = uri.hostname path = uri.path
port = uri.port

So that example requests may be written as:

Net::HTTP.get(uri) Net::HTTP.get(hostname, '/index.html') Net::HTTP.start(hostname) do |http| http.get('/todos/1') http.get('/todos/2') end

An example that needs a modified URI first duplicates uri, then modifies the duplicate:

_uri = uri.dup _uri.path = '/todos/1'

Returned Responses

Method Net::HTTP.get_response returns an instance of one of the subclasses of Net::HTTPResponse:

Net::HTTP.get_response(uri)

Net::HTTP.get_response(hostname, '/nosuch')

As does method Net::HTTP#request:

req = Net::HTTP::Get.new(uri) Net::HTTP.start(hostname) do |http| http.request(req) end

Class Net::HTTPResponse includes module Net::HTTPHeader, which provides access to response header values via (among others):

Examples:

res = Net::HTTP.get_response(uri) res['Content-Type']
res.content_type

Response Subclasses

Class Net::HTTPResponse has a subclass for each HTTP status code. You can look up the response class for a given code:

Net::HTTPResponse::CODE_TO_OBJ['200'] Net::HTTPResponse::CODE_TO_OBJ['400'] Net::HTTPResponse::CODE_TO_OBJ['404']

And you can retrieve the status code for a response object:

Net::HTTP.get_response(uri).code
Net::HTTP.get_response(hostname, '/nosuch').code

The response subclasses (indentation shows class hierarchy):

There is also the Net::HTTPBadResponse exception which is raised when there is a protocol error.