Class Net::HTTPResponse
In: lib/net/http.rb
Parent: Object

HTTP response class. This class wraps response header and entity. Mixes in the HTTPHeader module, which provides access to response header values both via hash-like methods and 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.

  xxx        HTTPResponse

    1xx        HTTPInformation
      100        HTTPContinue
      101        HTTPSwitchProtocol

    2xx        HTTPSuccess
      200        HTTPOK
      201        HTTPCreated
      202        HTTPAccepted
      203        HTTPNonAuthoritativeInformation
      204        HTTPNoContent
      205        HTTPResetContent
      206        HTTPPartialContent

    3xx        HTTPRedirection
      300        HTTPMultipleChoice
      301        HTTPMovedPermanently
      302        HTTPFound
      303        HTTPSeeOther
      304        HTTPNotModified
      305        HTTPUseProxy
      307        HTTPTemporaryRedirect

    4xx        HTTPClientError
      400        HTTPBadRequest
      401        HTTPUnauthorized
      402        HTTPPaymentRequired
      403        HTTPForbidden
      404        HTTPNotFound
      405        HTTPMethodNotAllowed
      406        HTTPNotAcceptable
      407        HTTPProxyAuthenticationRequired
      408        HTTPRequestTimeOut
      409        HTTPConflict
      410        HTTPGone
      411        HTTPLengthRequired
      412        HTTPPreconditionFailed
      413        HTTPRequestEntityTooLarge
      414        HTTPRequestURITooLong
      415        HTTPUnsupportedMediaType
      416        HTTPRequestedRangeNotSatisfiable
      417        HTTPExpectationFailed

    5xx        HTTPServerError
      500        HTTPInternalServerError
      501        HTTPNotImplemented
      502        HTTPBadGateway
      503        HTTPServiceUnavailable
      504        HTTPGatewayTimeOut
      505        HTTPVersionNotSupported

    xxx        HTTPUnknownResponse

Methods

Included Modules

HTTPHeader

Constants

CODE_CLASS_TO_OBJ = { '1' => HTTPInformation, '2' => HTTPSuccess, '3' => HTTPRedirection, '4' => HTTPClientError, '5' => HTTPServerError
CODE_TO_OBJ = { '100' => HTTPContinue, '101' => HTTPSwitchProtocol, '200' => HTTPOK, '201' => HTTPCreated, '202' => HTTPAccepted, '203' => HTTPNonAuthoritativeInformation, '204' => HTTPNoContent, '205' => HTTPResetContent, '206' => HTTPPartialContent, '300' => HTTPMultipleChoice, '301' => HTTPMovedPermanently, '302' => HTTPFound, '303' => HTTPSeeOther, '304' => HTTPNotModified, '305' => HTTPUseProxy, '307' => HTTPTemporaryRedirect, '400' => HTTPBadRequest, '401' => HTTPUnauthorized, '402' => HTTPPaymentRequired, '403' => HTTPForbidden, '404' => HTTPNotFound, '405' => HTTPMethodNotAllowed, '406' => HTTPNotAcceptable, '407' => HTTPProxyAuthenticationRequired, '408' => HTTPRequestTimeOut, '409' => HTTPConflict, '410' => HTTPGone, '411' => HTTPLengthRequired, '412' => HTTPPreconditionFailed, '413' => HTTPRequestEntityTooLarge, '414' => HTTPRequestURITooLong, '415' => HTTPUnsupportedMediaType, '416' => HTTPRequestedRangeNotSatisfiable, '417' => HTTPExpectationFailed, '500' => HTTPInternalServerError, '501' => HTTPNotImplemented, '502' => HTTPBadGateway, '503' => HTTPServiceUnavailable, '504' => HTTPGatewayTimeOut, '505' => HTTPVersionNotSupported

External Aliases

message -> msg

Attributes

code  [R]  HTTP result code string. For example, ‘302’. You can also determine the response type by which response subclass the response object is an instance of.
http_version  [R]  The HTTP version supported by the server.
message  [R]  HTTP result message. For example, ‘Not Found’.

Public Class methods

true if the response has body.

[Source]

      # File lib/net/http.rb, line 1784
1784:     def HTTPResponse.body_permitted?
1785:       self::HAS_BODY
1786:     end

Private Class methods

[Source]

      # File lib/net/http.rb, line 2032
2032:       def each_response_header(sock)
2033:         while true
2034:           line = sock.readuntil("\n", true).sub(/\s+\z/, '')
2035:           break if line.empty?
2036:           m = /\A([^:]+):\s*/.match(line) or
2037:               raise HTTPBadResponse, 'wrong header line format'
2038:           yield m[1], m.post_match
2039:         end
2040:       end

[Source]

      # File lib/net/http.rb, line 2019
2019:       def read_status_line(sock)
2020:         str = sock.readline
2021:         m = /\AHTTP(?:\/(\d+\.\d+))?\s+(\d\d\d)\s*(.*)\z/in.match(str) or
2022:           raise HTTPBadResponse, "wrong status line: #{str.dump}"
2023:         m.captures
2024:       end

[Source]

      # File lib/net/http.rb, line 2026
2026:       def response_class(code)
2027:         CODE_TO_OBJ[code] or
2028:         CODE_CLASS_TO_OBJ[code[0,1]] or
2029:         HTTPUnknownResponse
2030:       end

Public Instance methods

Returns the entity body.

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

  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
  }

[Source]

      # File lib/net/http.rb, line 2197
2197:     def body
2198:       read_body()
2199:     end
entity()

Alias for body

[Source]

      # File lib/net/http.rb, line 2070
2070:     def inspect
2071:       "#<#{self.class} #{@code} #{@message} readbody=#{@read}>"
2072:     end

Gets entity body. If the block given, yields it to block. The body is provided in fragments, as it is read in from the socket.

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

  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
  }

[Source]

      # File lib/net/http.rb, line 2165
2165:     def read_body(dest = nil, &block)
2166:       if @read
2167:         raise IOError, "#{self.class}\#read_body called twice" if dest or block
2168:         return @body
2169:       end
2170:       to = procdest(dest, block)
2171:       stream_check
2172:       if @body_exist
2173:         read_body_0 to
2174:         @body = to
2175:       else
2176:         @body = nil
2177:       end
2178:       @read = true
2179: 
2180:       @body
2181:     end

For backward compatibility. To allow Net::HTTP 1.1 style assignment e.g.

   response, body = Net::HTTP.get(....)

[Source]

      # File lib/net/http.rb, line 2079
2079:     def to_ary
2080:       warn "net/http.rb: warning: Net::HTTP v1.1 style assignment found at #{caller(1)[0]}; use `response = http.get(...)' instead." if $VERBOSE
2081:       res = self.dup
2082:       class << res
2083:         undef to_ary
2084:       end
2085:       [res, res.body]
2086:     end

Raises HTTP error if the response is not 2xx.

[Source]

      # File lib/net/http.rb, line 2105
2105:     def value
2106:       error! unless self.kind_of?(HTTPSuccess)
2107:     end

Private Instance methods

[Source]

      # File lib/net/http.rb, line 2244
2244:     def procdest(dest, block)
2245:       raise ArgumentError, 'both arg and block given for HTTP method' \
2246:           if dest and block
2247:       if block
2248:         ReadAdapter.new(block)
2249:       else
2250:         dest || ''
2251:       end
2252:     end

[Source]

      # File lib/net/http.rb, line 2205
2205:     def read_body_0(dest)
2206:       if chunked?
2207:         read_chunked dest
2208:         return
2209:       end
2210:       clen = content_length()
2211:       if clen
2212:         @socket.read clen, dest, true   # ignore EOF
2213:         return
2214:       end
2215:       clen = range_length()
2216:       if clen
2217:         @socket.read clen, dest
2218:         return
2219:       end
2220:       @socket.read_all dest
2221:     end

[Source]

      # File lib/net/http.rb, line 2223
2223:     def read_chunked(dest)
2224:       len = nil
2225:       total = 0
2226:       while true
2227:         line = @socket.readline
2228:         hexlen = line.slice(/[0-9a-fA-F]+/) or
2229:             raise HTTPBadResponse, "wrong chunk size line: #{line}"
2230:         len = hexlen.hex
2231:         break if len == 0
2232:         @socket.read len, dest; total += len
2233:         @socket.read 2   # \r\n
2234:       end
2235:       until @socket.readline.empty?
2236:         # none
2237:       end
2238:     end

[Source]

      # File lib/net/http.rb, line 2240
2240:     def stream_check
2241:       raise IOError, 'attempt to read body out of block' if @socket.closed?
2242:     end

[Validate]