Skip to content

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

instance method

Net::HTTPHeader#content_length=

(::Integer len) -> void
content_length=(len)

Sets the value of field 'Content-Length' to the given numeric; see Content-Length response header:

Example
_uri = uri.dup
hostname = _uri.hostname           # => "jsonplaceholder.typicode.com"
_uri.path = '/posts'               # => "/posts"
req = Net::HTTP::Post.new(_uri)    # => #<Net::HTTP::Post POST>
req.body = '{"title": "foo","body": "bar","userId": 1}'
req.content_length = req.body.size # => 42
req.content_type = 'application/json'
res = Net::HTTP.start(hostname) do |http|
  http.request(req)
end # => #<Net::HTTPCreated 201 Created readbody=true>