我确信这很容易,但我搜索得非常广泛而无法找到答案。我在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 。
答案 0 :(得分: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"]}
用于设置表单数据并检查标题和正文的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
答案 1 :(得分:1)
Net :: HTTP有一个名为set_debug_output的方法......它将打印您正在寻找的信息。
http = Net::HTTP.new
http.set_debug_output $stderr
http.start { .... }
答案 2 :(得分:0)
我认为您指的是请求标头,而不是请求正文。
要访问它,您可以查看Net :: HTTPHeader(http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTPHeader.html)的文档。该模块包含在Net :: HTTPRequest对象中,可以直接访问。
答案 3 :(得分: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}
其中的响应是这样的(注意响应的标题):
{"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"]}
答案 4 :(得分:-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 cheat sheet上找到这些和其他好的示例。