Get HTTP request in Ruby

The #to_hash method of a request object may be useful. Here's an example to build a GET request and inspect headers:

require 'net/http'
require 'uri'

uri = URI('http://example.com/cached_response')
req = Net::HTTP::Get.new(uri.request_uri)

req['X-Crazy-Header'] = "This is crazy"

puts req.to_hash # hash of request headers
# => {"accept"=>["*/*"], "user-agent"=>["Ruby"], "x-crazy-header"=>["This is crazy"]}

And an example for a POST request to set form data and inspect headers and body:

require 'net/http'
require 'uri'

uri = URI('http://www.example.com/todo.cgi')
req = Net::HTTP::Post.new(uri.path)

req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31')

puts req.to_hash # hash of request headers
# => {"accept"=>["*/*"], "user-agent"=>["Ruby"], "content-type"=>["application/x-www-form-urlencoded"]}

puts req.body # string of request body
# => from=2005-01-01&to=2005-03-31

Net::HTTP has a method called set_debug_output... It will print the information you're looking for.

http = Net::HTTP.new
http.set_debug_output $stderr
http.start { .... }

Tags:

Ruby

Request