Setting header in POST request

If we also would like to set fields in the header we need a slightly more complex way of writing this:

First we need to create a request object using Net::HTTP::Post. Then add the form data using the set_form_data method. Finally add a few key-value pairs directly to the request.

Then we need to start the HTTP session and send the request using the request method.`

When we called start we had to supply the hostname and the port manually and because our URL is https (and not http) we also need to set :use_ssl => true in order for this to work.

require 'net/http'

url = ''
uri = URI(url)

req =
   "name" => "Foo Bar",
   "height" => 175,
req['User-Agent'] = "Internet Explorer 6.0"
req['X-Answer'] = 42

response = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|

if response.is_a?(Net::HTTPSuccess)
    puts response.body
    puts response.code

  "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": "", 
    "User-Agent": "Internet Explorer 6.0", 
    "X-Amzn-Trace-Id": "Root=1-6394ce2e-2722ccb67d44f1ee1691a05a", 
    "X-Answer": "42"
  "json": null, 
  "origin": "", 
  "url": ""