繁体   English   中英

在 Ruby 中显示 HTTP 请求的标头和正文文本

[英]Show headers and body text of an HTTP request in Ruby

我确信这很容易,但我已经进行了相当广泛的搜索,但无法找到答案。 我在 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 对象中,可以直接访问。

如果您想对来自请求的响应( GET调用)执行更复杂的操作,此示例显示了如何执行GET并从响应中读取标头:

  access_token = API::TokenManager.valid_token
  config = Rails.configuration.my_web_app["api"]
  uri = URI("#{config.fetch("base_url")}/api_endpoint?access_token=#{access_token}")
  response = Net::HTTP.get_response(uri)
  puts response.to_hash["x-app-usage"]["call_count"]

=> {"call_count":48,"total_cputime":0,"total_time":80}

响应是这样的(注意响应的标题):

{"etag"=>["\"123\""], "x-app-usage"=>["{\"call_count\":48,\"total_cputime\":0,\"total_time\":80}"], "content-type"=>["application/json; charset=UTF-8"], "api-version"=>["v3.3"], "strict-transport-security"=>["max-age=15552000; preload"], "pragma"=>["no-cache"], "x-api-rev"=>["1002669385"], "access-control-allow-origin"=>["*"], "cache-control"=>["private, no-cache, no-store, must-revalidate"], "x-api-trace-id"=>["AD5Ou+tTNzs"], "x-api-request-id"=>["xxx"], "expires"=>["Sat, 01 Jan 2000 00:00:00 GMT"], "x-api-debug"=>["xxxxxxx=="], "date"=>["Wed, 16 Sep 2020 00:11:13 GMT"], "alt-svc"=>["h3-29=\":443\"; ma=3600,h3-27=\":443\"; ma=3600"], "connection"=>["keep-alive"], "content-length"=>["53"]}

这是最基本的 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 备忘单上找到这些和其他很好的示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM