在Ruby中获取HTTP请求

wir*_*bor 8 ruby request

我确信这很容易,但我搜索得非常广泛而且无法找到答案.我在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
Run Code Online (Sandbox Code Playgroud)

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

ros*_*sta 9

请求对象的#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"]}
Run Code Online (Sandbox Code Playgroud)

以及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
Run Code Online (Sandbox Code Playgroud)