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 1793
1793:     def HTTPResponse.body_permitted?
1794:       self::HAS_BODY
1795:     end

Private Class methods

[Source]

      # File lib/net/http.rb, line 2041
2041:       def each_response_header(sock)
2042:         while true
2043:           line = sock.readuntil("\n", true).sub(/\s+\z/, '')
2044:           break if line.empty?
2045:           m = /\A([^:]+):\s*/.match(line) or
2046:               raise HTTPBadResponse, 'wrong header line format'
2047:           yield m[1], m.post_match
2048:         end
2049:       end

[Source]

      # File lib/net/http.rb, line 2028
2028:       def read_status_line(sock)
2029:         str = sock.readline
2030:         m = /\AHTTP(?:\/(\d+\.\d+))?\s+(\d\d\d)\s*(.*)\z/in.match(str) or
2031:           raise HTTPBadResponse, "wrong status line: #{str.dump}"
2032:         m.captures
2033:       end

[Source]

      # File lib/net/http.rb, line 2035
2035:       def response_class(code)
2036:         CODE_TO_OBJ[code] or
2037:         CODE_CLASS_TO_OBJ[code[0,1]] or
2038:         HTTPUnknownResponse
2039:       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 2206
2206:     def body
2207:       read_body()
2208:     end
entity()

Alias for body

[Source]

      # File lib/net/http.rb, line 2079
2079:     def inspect
2080:       "#<#{self.class} #{@code} #{@message} readbody=#{@read}>"
2081:     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 2174
2174:     def read_body(dest = nil, &block)
2175:       if @read
2176:         raise IOError, "#{self.class}\#read_body called twice" if dest or block
2177:         return @body
2178:       end
2179:       to = procdest(dest, block)
2180:       stream_check
2181:       if @body_exist
2182:         read_body_0 to
2183:         @body = to
2184:       else
2185:         @body = nil
2186:       end
2187:       @read = true
2188: 
2189:       @body
2190:     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 2088
2088:     def to_ary
2089:       warn "net/http.rb: warning: Net::HTTP v1.1 style assignment found at #{caller(1)[0]}; use `response = http.get(...)' instead." if $VERBOSE
2090:       res = self.dup
2091:       class << res
2092:         undef to_ary
2093:       end
2094:       [res, res.body]
2095:     end

Raises HTTP error if the response is not 2xx.

[Source]

      # File lib/net/http.rb, line 2114
2114:     def value
2115:       error! unless self.kind_of?(HTTPSuccess)
2116:     end

Private Instance methods

[Source]

      # File lib/net/http.rb, line 2253
2253:     def procdest(dest, block)
2254:       raise ArgumentError, 'both arg and block given for HTTP method' \
2255:           if dest and block
2256:       if block
2257:         ReadAdapter.new(block)
2258:       else
2259:         dest || ''
2260:       end
2261:     end

[Source]

      # File lib/net/http.rb, line 2214
2214:     def read_body_0(dest)
2215:       if chunked?
2216:         read_chunked dest
2217:         return
2218:       end
2219:       clen = content_length()
2220:       if clen
2221:         @socket.read clen, dest, true   # ignore EOF
2222:         return
2223:       end
2224:       clen = range_length()
2225:       if clen
2226:         @socket.read clen, dest
2227:         return
2228:       end
2229:       @socket.read_all dest
2230:     end

[Source]

      # File lib/net/http.rb, line 2232
2232:     def read_chunked(dest)
2233:       len = nil
2234:       total = 0
2235:       while true
2236:         line = @socket.readline
2237:         hexlen = line.slice(/[0-9a-fA-F]+/) or
2238:             raise HTTPBadResponse, "wrong chunk size line: #{line}"
2239:         len = hexlen.hex
2240:         break if len == 0
2241:         @socket.read len, dest; total += len
2242:         @socket.read 2   # \r\n
2243:       end
2244:       until @socket.readline.empty?
2245:         # none
2246:       end
2247:     end

[Source]

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

[Validate]