class Net::HTTPResponse

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

关于示例

此处的示例假设已加载 net/http(这也将加载 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 异常,当出现协议错误时会引发该异常。