Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show headers and body text of an HTTP request in Ruby

Tags:

ruby

request

I'm sure this is easy, but I've searched pretty extensively and been unable to find an answer. I'm using the Net::Http library in Ruby and am trying to figure out how I show the complete body of an HTTP GET request? Something like the following:

GET /really_long_path/index.html?q=foo&s=bar HTTP\1.1
Cookie: some_cookie;
Host: remote_host.example.com

I am looking for the raw REQUEST , not the RESPONSE to be captured.

like image 474
wireharbor Avatar asked Oct 11 '12 20:10

wireharbor


1 Answers

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
like image 70
rossta Avatar answered Oct 04 '22 18:10

rossta