在发出请求之前从Ruby Net :: HTTP请求获取标头 [英] Getting Headers from a Ruby Net::HTTP Request before making the request

查看:240
本文介绍了在发出请求之前从Ruby Net :: HTTP请求获取标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,在实际发出请求之前,我如何掌握将由net/http或open-uri请求发送的HTTP请求标头.

In Ruby, how can I get hold of the HTTP Request Headers that will be sent by a net/http(s) or open-uri request BEFORE it actually makes the request.

在某些情况下,在URI中创建签名字符串时会使用标头.当然,有一些方法可以获取将要发送的请求标头.例如,这些名称应包含"Host:"标头.

In some cases, headers are used when creating a signed string in a URI. Surely there is some way to acquire the request headers that will be sent. These should include the "Host:" header for example.

推荐答案

请参见在ruby 2.0.0中效果很好-但是您是正确的,在1.9.3中有不同的行为

Works well in ruby 2.0.0 - but you are correct, different behavior in 1.9.3

require 'net/http'
uri = URI('http://github.com/ruby')

http_request = Net::HTTP::Get.new(uri)
http_request.each_header { |header| puts header }

# => accept-encoding
# => accept
# => user-agent
# => host    

http_response = Net::HTTP.start(uri.hostname, uri.port) do |http|
  http.request(http_request)
end

Ruby 1.9.3

require 'uri'
require 'net/http'
uri = URI.parse('http://github.com/ruby')

http_request = Net::HTTP::Get.new(uri.path)
http_request.each_header { |header| puts header }

# => accept
# => user-agent

http_response = Net::HTTP.start(uri.hostname, uri.port) do |http|
  http.request(http_request)
end

http_request.each_header { |header| puts header }

# => accept
# => user-agent
# => host

这篇关于在发出请求之前从Ruby Net :: HTTP请求获取标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆