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.


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

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

req = Net::HTTP::Post.new(uri)
req.set_form_data(
   "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|
  http.request(req)
end

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

{
  "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": "Internet Explorer 6.0", 
    "X-Amzn-Trace-Id": "Root=1-6394ce2e-2722ccb67d44f1ee1691a05a", 
    "X-Answer": "42"
  }, 
  "json": null, 
  "origin": "46.120.8.206", 
  "url": "https://httpbin.org/post"
}