【问题标题】:Ruby Net::HTTP passing headers through the creation of requestRuby Net::HTTP 通过创建请求传递标头
【发布时间】:2020-09-13 20:14:47
【问题描述】:

也许我只是瞎了眼,但是很多关于在 Net::HTTP 中传递标头的帖子都遵循

require 'net/http'    

uri = URI("http://www.ruby-lang.org")
req = Net::HTTP::Get.new(uri)
req['some_header'] = "some_val"

res = Net::HTTP.start(uri.hostname, uri.port) {|http|
  http.request(req)
}

puts res.body

(来自Ruby - Send GET request with headers隐喻的回答)

来自 Net::HTTP 文档 (https://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html)

uri = URI('http://example.com/cached_response')
file = File.stat 'cached_response'

req = Net::HTTP::Get.new(uri)
req['If-Modified-Since'] = file.mtime.rfc2822

res = Net::HTTP.start(uri.hostname, uri.port) {|http|
  http.request(req)
}

open 'cached_response', 'w' do |io|
  io.write res.body
end if res.is_a?(Net::HTTPSuccess)

但是当您可以通过以下方式传递标头时,执行上述操作有什么好处?

options = { 
  'headers' => {
    'Content-Type' => 'application/json'
  }
}

request = Net::HTTP::Get.new('http://www.stackoverflow.com/', options['headers'])

这允许您参数化标头,并且可以非常轻松地允许多个标头。

我的主要问题是,在创建 Net::HTTP::Get 时传递标头与在创建 Net::HTTP::Get 后传递标头有什么优势

Net::HTTPHeader 已经开始并在函数中分配标头

def initialize_http_header(initheader)
    @header = {}
    return unless initheader
    initheader.each do |key, value|
      warn "net/http: duplicated HTTP header: #{key}", uplevel: 1 if key?(key) and $VERBOSE
      if value.nil?
        warn "net/http: nil HTTP header: #{key}", uplevel: 1 if $VERBOSE
      else
        value = value.strip # raise error for invalid byte sequences
        if value.count("\r\n") > 0
          raise ArgumentError, 'header field value cannot include CR/LF'
        end
        @header[key.downcase] = [value]
      end
    end
  end

这样做 request['some_header'] = "some_val" 几乎就像代码重复。

【问题讨论】:

    标签: ruby net-http ruby-2.5


    【解决方案1】:

    以一种或另一种方式设置标题没有任何优势,至少不是我能想到的。这取决于您自己的喜好。事实上,如果你看一下在初始化一个新的 Net::Http::Get 时提供 headers 会发生什么,你会发现在内部,Ruby 只是将 headers 设置为 @headers 变量: https://github.com/ruby/ruby/blob/c5eb24349a4535948514fe765c3ddb0628d81004/lib/net/http/header.rb#L25

    如果您使用request[name] = value 设置标头,您可以看到 Net::Http 执行完全相同的操作,但方法不同: https://github.com/ruby/ruby/blob/c5eb24349a4535948514fe765c3ddb0628d81004/lib/net/http/header.rb#L46

    因此,无论您决定以哪种方式传递请求标头,生成的对象都具有相同的配置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-20
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      • 2011-11-22
      • 2023-03-28
      • 2013-06-09
      相关资源
      最近更新 更多