11

我确信这很容易,但我已经进行了相当广泛的搜索,但无法找到答案。我Net::Http在 Ruby 中使用该库,并试图弄清楚如何显示 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 。

4

5 回答 5

12

请求对象的 #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
于 2012-10-11T22:35:46.857 回答
2

Net::HTTP 有一个名为set_debug_output的方法......它将打印您正在寻找的信息。

http = Net::HTTP.new
http.set_debug_output $stderr
http.start { .... }
于 2012-10-11T21:28:45.687 回答
0

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

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

于 2012-10-11T20:54:39.407 回答
0

如果您想对来自请求(调用)的响应做一些更复杂的事情,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}

Where the response is something like this (notice the headers of the response):

{"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"]}
于 2020-09-16T00:23:04.703 回答
-1

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

于 2012-10-11T20:31:13.887 回答