Get HTTP request in Ruby

I am sure this is easy, but I searched quite widely and could not find the answer. Am I using the Net :: Http library in Ruby and trying to figure out how I am displaying the full text 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 a raw REQUEST , not RESPONSE .

+6
source share
4 answers

The #to_hash method of the request object may be useful. Here's an example of creating a GET request and checking the 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 of a POST request for setting form data and checking 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 
+9
source

Net :: HTTP has the set_debug_output method ... It will print the information you need.

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

I think you mean the request headers, not the request body.

To access this, you can look at the documentation for Net :: HTTPHeader ( http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTPHeader.html ). This module is included in Net :: HTTPRequest objects that can be accessed directly.

0
source

This is the simplest Net :: HTTP example:

 require "net/http" require "uri" uri = URI.parse("http://google.com/") # Will print response.body Net::HTTP.get_print(uri) # OR # Get the response response = Net::HTTP.get_response(uri) puts response.body 

You can find these and other good examples on Net: HTTP cheat sheet .

-1
source

Source: https://habr.com/ru/post/927504/


All Articles