Sending a POST request


There is more to do with GET requests, but before we go on, let's also see how to send simple POST requests.

First of all HTTPbin expects the POST requests to arrive to a different end-point called, /post.

In order to send a POST request we call the post_form method. Pass the URI to it and a hash of the data. The hash can be empty but it mist be provided. In our case I just provided it with two keys-value pairs.


examples/net-http/post_response_get_httpbin.rb
require 'net/http'

url = 'https://httpbin.org/post'
uri = URI(url)

response = Net::HTTP.post_form(uri, {
   "name" => "Foo Bar",
   "height" => 175,
  },
)
if response.is_a?(Net::HTTPSuccess)
    puts response.body
else
    puts response.code
end

This is the response. HTTPbin was kind enough to send back the form-data so we can verify that it was sent and received properly.


{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "height": "175",
    "name": "Foo Bar"
  },
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip;q=1.0,deflate;q=0.6,identity;q=0.3",
    "Content-Length": "23",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "httpbin.org",
    "User-Agent": "Ruby",
    "X-Amzn-Trace-Id": "Root=1-6394c45b-3378e8395614f5c35db23677"
  },
  "json": null,
  "origin": "46.120.8.206",
  "url": "https://httpbin.org/post"
}