繁体   English   中英

Ruby Net::HTTP 通过创建请求传递 headers

[英]Ruby Net::HTTP passing headers through the creation of request

也许我只是盲目,但许多关于在 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 - 发送带有标题隐喻的 GET 请求的答案)

并来自 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 已经开始并分配了 function 中的标头

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"几乎看起来像代码重复。

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

And if you set the headers using request[name] = value , you can see that Net::Http does the exact same thing, but in a different method: https://github.com/ruby/ruby/blob/c5eb24349a4535948514fe765c3ddb0628d81004/ lib/net/http/header.rb#L46

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

暂无
暂无

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

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