在Ruby中获取HTTP请求

我确信这很容易,但我搜索得非常广泛而无法找到答案。 我在Ruby中使用Net :: Http库,并试图找出如何显示HTTP GET请求的完整主体? 类似于以下内容:

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

我正在寻找原始的REQUEST ,而不是要捕获的RESPONSE

请求对象的#to_hash方法可能很有用。 这是一个构建GET请求并检查标头的示例:

 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"]} 

以及POST请求设置表单数据和检查标题和正文的示例:

 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有一个名为set_debug_output的方法……它将打印您正在寻找的信息。

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

我认为您指的是请求标头,而不是请求正文。

要访问它,您可以查看Net :: HTTPHeader( http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTPHeader.html )的文档。 此模块包含在Net :: HTTPRequest对象中,可以直接访问。

这是最基本的Net :: HTTP示例:

 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 

您可以在Net:HTTP备忘单上找到这些和其他好的示例。