簡體   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