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 1781
1781:     def HTTPResponse.body_permitted?
1782:       self::HAS_BODY
1783:     end

Private Class methods

[Source]

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

[Source]

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

[Source]

      # File lib/net/http.rb, line 2023
2023:       def response_class(code)
2024:         CODE_TO_OBJ[code] or
2025:         CODE_CLASS_TO_OBJ[code[0,1]] or
2026:         HTTPUnknownResponse
2027:       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 2194
2194:     def body
2195:       read_body()
2196:     end
entity()

Alias for body

[Source]

      # File lib/net/http.rb, line 2067
2067:     def inspect
2068:       "#<#{self.class} #{@code} #{@message} readbody=#{@read}>"
2069:     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 2162
2162:     def read_body(dest = nil, &block)
2163:       if @read
2164:         raise IOError, "#{self.class}\#read_body called twice" if dest or block
2165:         return @body
2166:       end
2167:       to = procdest(dest, block)
2168:       stream_check
2169:       if @body_exist
2170:         read_body_0 to
2171:         @body = to
2172:       else
2173:         @body = nil
2174:       end
2175:       @read = true
2176: 
2177:       @body
2178:     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 2076
2076:     def to_ary
2077:       warn "net/http.rb: warning: Net::HTTP v1.1 style assignment found at #{caller(1)[0]}; use `response = http.get(...)' instead." if $VERBOSE
2078:       res = self.dup
2079:       class << res
2080:         undef to_ary
2081:       end
2082:       [res, res.body]
2083:     end

Raises HTTP error if the response is not 2xx.

[Source]

      # File lib/net/http.rb, line 2102
2102:     def value
2103:       error! unless self.kind_of?(HTTPSuccess)
2104:     end

Private Instance methods

[Source]

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

[Source]

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

[Source]

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

[Source]

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

[Validate]