class Net::HTTPResponse

此类是 Net::HTTP 响应类的基类。

关于示例

此处的示例假设已 require 了 net/http (这也 require 了 uri)

require 'net/http'

此处的许多代码示例使用这些示例网站

一些示例还假设这些变量

uri = URI('https://jsonplaceholder.typicode.com/')
uri.freeze # Examples may not modify.
hostname = uri.hostname # => "jsonplaceholder.typicode.com"
path = uri.path         # => "/"
port = uri.port         # => 443

以便示例请求可以写成

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

一个需要修改 URI 的示例,首先复制 uri,然后修改副本

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

返回的响应

方法 Net::HTTP.get_response 返回 Net::HTTPResponse 的子类之一的实例

Net::HTTP.get_response(uri)
# => #<Net::HTTPOK 200 OK readbody=true>
Net::HTTP.get_response(hostname, '/nosuch')
# => #<Net::HTTPNotFound 404 Not Found readbody=true>

方法 Net::HTTP#request 也是如此

req = Net::HTTP::Get.new(uri)
Net::HTTP.start(hostname) do |http|
  http.request(req)
end # => #<Net::HTTPOK 200 OK readbody=true>

类 Net::HTTPResponse 包含模块 Net::HTTPHeader,它提供通过以下方式(以及其他方式)访问响应头值的功能:

示例

res = Net::HTTP.get_response(uri) # => #<Net::HTTPOK 200 OK readbody=true>
res['Content-Type']               # => "text/html; charset=UTF-8"
res.content_type                  # => "text/html"

响应子类

类 Net::HTTPResponse 为每个 HTTP 状态码都有一个子类。您可以查找给定代码的响应类

Net::HTTPResponse::CODE_TO_OBJ['200'] # => Net::HTTPOK
Net::HTTPResponse::CODE_TO_OBJ['400'] # => Net::HTTPBadRequest
Net::HTTPResponse::CODE_TO_OBJ['404'] # => Net::HTTPNotFound

您可以检索响应对象的状态码

Net::HTTP.get_response(uri).code                 # => "200"
Net::HTTP.get_response(hostname, '/nosuch').code # => "404"

响应子类(缩进显示类层次结构)

当出现协议错误时,还会引发 Net::HTTPBadResponse 异常。