Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Net::HTTPResponse#read_body

() -> ::String
(::Net::HTTPResponse::_Dest dest) -> ::String
() { (::String) -> void } -> ::String
read_body(dest = nil, &block)

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.

If dest argument is given, response is read into that variable, with dest#<< method (it could be String or IO, or any other object responding to <<).

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

Example
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
}
See also #inspect #value #body_encoding= also in 3.3 · 3.2 · 3.1 · 3.0