Method: Gem::Net::HTTP#post

Defined in:
lib/rubygems/vendor/net-http/lib/net/http.rb

#post(path, data, initheader = nil, dest = nil, &block) ⇒ Object

:call-seq:

post(path, data, initheader = nil) {|res| ... }

Sends a POST request to the server; returns an instance of a subclass of Gem::Net::HTTPResponse.

The request is based on the Gem::Net::HTTP::Post object created from string path, string data, and initial headers hash initheader.

With a block given, calls the block with the response body:

data = '{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'
http = Gem::Net::HTTP.new(hostname)
http.post('/todos', data) do |res|
  p res
end # => #<Gem::Net::HTTPCreated 201 Created readbody=true>

Output:

"{\n  \"{\\\"userId\\\": 1, \\\"id\\\": 1, \\\"title\\\": \\\"delectus aut autem\\\", \\\"completed\\\": false}\": \"\",\n  \"id\": 201\n}"

With no block given, simply returns the response object:

http.post('/todos', data) # => #<Gem::Net::HTTPCreated 201 Created readbody=true>

Related:

  • Gem::Net::HTTP::Post: request class for HTTP method POST.

  • Gem::Net::HTTP.post: sends POST request, returns response body.



2045
2046
2047
# File 'lib/rubygems/vendor/net-http/lib/net/http.rb', line 2045

def post(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
  send_entity(path, data, initheader, dest, Post, &block)
end