Class: Net::HTTPResponse

Inherits:
Object
  • Object
show all
Includes:
HTTPHeader
Defined in:
lib/net/http/response.rb,
lib/net/http/responses.rb

Overview

HTTP response class.

This class wraps together the response header and the response body (the entity requested).

It mixes in the HTTPHeader module, which provides access to response header values both via hash-like methods and via individual readers.

Note that each possible HTTP response code defines its own HTTPResponse subclass. These are listed below.

All classes are defined under the Net module. Indentation indicates inheritance. For a list of the classes see Net::HTTP.

Defined Under Namespace

Classes: Inflater

Constant Summary collapse

CODE_CLASS_TO_OBJ =
{
  '1' => Net::HTTPInformation,
  '2' => Net::HTTPSuccess,
  '3' => Net::HTTPRedirection,
  '4' => Net::HTTPClientError,
  '5' => Net::HTTPServerError
}
CODE_TO_OBJ =
{
  '100' => Net::HTTPContinue,
  '101' => Net::HTTPSwitchProtocol,

  '200' => Net::HTTPOK,
  '201' => Net::HTTPCreated,
  '202' => Net::HTTPAccepted,
  '203' => Net::HTTPNonAuthoritativeInformation,
  '204' => Net::HTTPNoContent,
  '205' => Net::HTTPResetContent,
  '206' => Net::HTTPPartialContent,
  '207' => Net::HTTPMultiStatus,
  '226' => Net::HTTPIMUsed,

  '300' => Net::HTTPMultipleChoices,
  '301' => Net::HTTPMovedPermanently,
  '302' => Net::HTTPFound,
  '303' => Net::HTTPSeeOther,
  '304' => Net::HTTPNotModified,
  '305' => Net::HTTPUseProxy,
  '307' => Net::HTTPTemporaryRedirect,

  '400' => Net::HTTPBadRequest,
  '401' => Net::HTTPUnauthorized,
  '402' => Net::HTTPPaymentRequired,
  '403' => Net::HTTPForbidden,
  '404' => Net::HTTPNotFound,
  '405' => Net::HTTPMethodNotAllowed,
  '406' => Net::HTTPNotAcceptable,
  '407' => Net::HTTPProxyAuthenticationRequired,
  '408' => Net::HTTPRequestTimeOut,
  '409' => Net::HTTPConflict,
  '410' => Net::HTTPGone,
  '411' => Net::HTTPLengthRequired,
  '412' => Net::HTTPPreconditionFailed,
  '413' => Net::HTTPRequestEntityTooLarge,
  '414' => Net::HTTPRequestURITooLong,
  '415' => Net::HTTPUnsupportedMediaType,
  '416' => Net::HTTPRequestedRangeNotSatisfiable,
  '417' => Net::HTTPExpectationFailed,
  '422' => Net::HTTPUnprocessableEntity,
  '423' => Net::HTTPLocked,
  '424' => Net::HTTPFailedDependency,
  '426' => Net::HTTPUpgradeRequired,
  '428' => Net::HTTPPreconditionRequired,
  '429' => Net::HTTPTooManyRequests,
  '431' => Net::HTTPRequestHeaderFieldsTooLarge,

  '500' => Net::HTTPInternalServerError,
  '501' => Net::HTTPNotImplemented,
  '502' => Net::HTTPBadGateway,
  '503' => Net::HTTPServiceUnavailable,
  '504' => Net::HTTPGatewayTimeOut,
  '505' => Net::HTTPVersionNotSupported,
  '507' => Net::HTTPInsufficientStorage,
  '511' => Net::HTTPNetworkAuthenticationRequired,
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from HTTPHeader

#[], #[]=, #add_field, #basic_auth, #chunked?, #connection_close?, #connection_keep_alive?, #content_length, #content_length=, #content_range, #content_type, #delete, #each_capitalized, #each_capitalized_name, #each_header, #each_name, #each_value, #fetch, #get_fields, #initialize_http_header, #key?, #main_type, #proxy_basic_auth, #range, #range_length, #set_content_type, #set_form, #set_form_data, #set_range, #size, #sub_type, #to_hash, #type_params

Constructor Details

#initialize(httpv, code, msg) ⇒ HTTPResponse

:nodoc: internal use only



75
76
77
78
79
80
81
82
83
84
# File 'lib/net/http/response.rb', line 75

def initialize(httpv, code, msg)   #:nodoc: internal use only
  @http_version = httpv
  @code         = code
  @message      = msg
  initialize_http_header nil
  @body = nil
  @read = false
  @uri  = nil
  @decode_content = false
end

Instance Attribute Details

#codeObject (readonly)

The HTTP result code string. For example, ‘302’. You can also determine the response type by examining which response subclass the response object is an instance of.



92
93
94
# File 'lib/net/http/response.rb', line 92

def code
  @code
end

#decode_contentObject

Set to true automatically when the request did not contain an Accept-Encoding header from the user.



104
105
106
# File 'lib/net/http/response.rb', line 104

def decode_content
  @decode_content
end

#http_versionObject (readonly)

The HTTP version supported by the server.



87
88
89
# File 'lib/net/http/response.rb', line 87

def http_version
  @http_version
end

#messageObject (readonly) Also known as: msg

The HTTP result message sent by the server. For example, ‘Not Found’.



95
96
97
# File 'lib/net/http/response.rb', line 95

def message
  @message
end

#uriObject

The URI used to fetch this response. The response URI is only available if a URI was used to create the request.



100
101
102
# File 'lib/net/http/response.rb', line 100

def uri
  @uri
end

Class Method Details

.body_permitted?Boolean

true if the response has a body.

Returns:

  • (Boolean)


19
20
21
# File 'lib/net/http/response.rb', line 19

def body_permitted?
  self::HAS_BODY
end

.exception_typeObject

:nodoc: internal use only



23
24
25
# File 'lib/net/http/response.rb', line 23

def exception_type   # :nodoc: internal use only
  self::EXCEPTION_TYPE
end

.read_new(sock) ⇒ Object

:nodoc: internal use only



27
28
29
30
31
32
33
34
# File 'lib/net/http/response.rb', line 27

def read_new(sock)   #:nodoc: internal use only
  httpv, code, msg = read_status_line(sock)
  res = response_class(code).new(httpv, code, msg)
  each_response_header(sock) do |k,v|
    res.add_field k, v
  end
  res
end

Instance Method Details

#bodyObject Also known as: entity

Returns the full entity body.

Calling this method a second or subsequent time will return the string already read.

http.request_get('/index.html') {|res|
  puts res.body
}

http.request_get('/index.html') {|res|
  p res.body.object_id   # 538149362
  p res.body.object_id   # 538149362
}


225
226
227
# File 'lib/net/http/response.rb', line 225

def body
  read_body()
end

#body=(value) ⇒ Object

Because it may be necessary to modify the body, Eg, decompression this method facilitates that.



231
232
233
# File 'lib/net/http/response.rb', line 231

def body=(value)
  @body = value
end

#code_typeObject

response <-> exception relationship



114
115
116
# File 'lib/net/http/response.rb', line 114

def code_type   #:nodoc:
  self.class
end

#error!Object

:nodoc:

Raises:



118
119
120
# File 'lib/net/http/response.rb', line 118

def error!   #:nodoc:
  raise error_type().new(@code + ' ' + @message.dump, self)
end

#error_typeObject

:nodoc:



122
123
124
# File 'lib/net/http/response.rb', line 122

def error_type   #:nodoc:
  self.class::EXCEPTION_TYPE
end

#headerObject

:nodoc:



144
145
146
147
# File 'lib/net/http/response.rb', line 144

def header   #:nodoc:
  warn "#{caller(1)[0]}: warning: Net::HTTPResponse#header is obsolete" if $VERBOSE
  self
end

#inspectObject



106
107
108
# File 'lib/net/http/response.rb', line 106

def inspect
  "#<#{self.class} #{@code} #{@message} readbody=#{@read}>"
end

#read_body(dest = nil, &block) ⇒ Object

Gets the entity body returned by the remote HTTP server.

If a block is given, the body is passed to the block, and the body is provided in fragments, as it is read in from the socket.

Calling this method a second or subsequent time for the same HTTPResponse object will return the value already read.

http.request_get('/index.html') {|res|
  puts res.read_body
}

http.request_get('/index.html') {|res|
  p res.read_body.object_id   # 538149362
  p res.read_body.object_id   # 538149362
}

# using iterator
http.request_get('/index.html') {|res|
  res.read_body do |segment|
    print segment
  end
}


193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/net/http/response.rb', line 193

def read_body(dest = nil, &block)
  if @read
    raise IOError, "#{self.class}\#read_body called twice" if dest or block
    return @body
  end
  to = procdest(dest, block)
  stream_check
  if @body_exist
    read_body_0 to
    @body = to
  else
    @body = nil
  end
  @read = true

  @body
end

#read_headerObject

:nodoc:



149
150
151
152
# File 'lib/net/http/response.rb', line 149

def read_header   #:nodoc:
  warn "#{caller(1)[0]}: warning: Net::HTTPResponse#read_header is obsolete" if $VERBOSE
  self
end

#reading_body(sock, reqmethodallowbody) ⇒ Object

body



158
159
160
161
162
163
164
165
166
167
# File 'lib/net/http/response.rb', line 158

def reading_body(sock, reqmethodallowbody)  #:nodoc: internal use only
  @socket = sock
  @body_exist = reqmethodallowbody && self.class.body_permitted?
  begin
    yield
    self.body   # ensure to read body
  ensure
    @socket = nil
  end
end

#responseObject

header (for backward compatibility only; DO NOT USE)



139
140
141
142
# File 'lib/net/http/response.rb', line 139

def response   #:nodoc:
  warn "#{caller(1)[0]}: warning: Net::HTTPResponse#response is obsolete" if $VERBOSE
  self
end

#valueObject

Raises an HTTP error if the response is not 2xx (success).



127
128
129
# File 'lib/net/http/response.rb', line 127

def value
  error! unless self.kind_of?(Net::HTTPSuccess)
end