module Net::HTTPHeader
HTTPHeader 模块提供对 HTTP 头的访问。
该模块包含在
头是键/值对的哈希状集合,称为字段。
请求和响应字段
头可能包含在
-
A
Net::HTTPRequest对象中:对象的头将随请求一起发送。请求中可以定义任何字段;请参阅 Setters。 -
A
Net::HTTPResponse对象中:对象的头通常是从主机返回的头。可以从对象中检索字段;请参阅 Getters 和 Iterators。
究竟哪些字段应该被发送或预期取决于主机;请参阅
关于示例
此处的示例假设已加载 net/http(这也将加载 uri)
require 'net/http'
这里的许多代码示例都使用了这些示例网站
一些示例还假定存在这些变量
uri = URI('https://jsonplaceholder.typicode.com/') uri.freeze # Examples may not modify. hostname = uri.hostname # => "jsonplaceholder.typicode.com" path = uri.path # => "/" port = uri.port # => 443
因此,示例请求可以这样编写
Net::HTTP.get(uri) Net::HTTP.get(hostname, '/index.html') Net::HTTP.start(hostname) do |http| http.get('/todos/1') http.get('/todos/2') end
需要修改 URI 的示例首先复制 uri,然后修改副本
_uri = uri.dup _uri.path = '/todos/1'
字段
头字段是键/值对。
字段键
字段键可以是
-
字符串:键
'Accept'被视为'Accept'.downcase;即'accept'。 -
符号:键
:Accept被视为:Accept.to_s.downcase;即'accept'。
示例
req = Net::HTTP::Get.new(uri) req[:accept] # => "*/*" req['Accept'] # => "*/*" req['ACCEPT'] # => "*/*" req['accept'] = 'text/html' req[:accept] = 'text/html' req['ACCEPT'] = 'text/html'
字段值
字段值可以返回为字符串数组或字符串。
-
这些方法返回字段值作为数组。
-
get_fields:返回给定键的数组值,如果不存在则返回nil。 -
to_hash:返回所有头字段的哈希:每个键是一个字段名;其值是该字段的数组值。
-
-
这些方法返回字段值作为字符串;字段的字符串值等同于
self[key.downcase.to_s].join(', '))。
字段值可以设置
示例字段值
-
String
req['Accept'] = 'text/html' # => "text/html" req['Accept'] # => "text/html" req.get_fields('Accept') # => ["text/html"]
-
Symbol
req['Accept'] = :text # => :text req['Accept'] # => "text" req.get_fields('Accept') # => ["text"]
-
简单数组
req[:foo] = %w[bar baz bat] req[:foo] # => "bar, baz, bat" req.get_fields(:foo) # => ["bar", "baz", "bat"]
-
简单哈希
req[:foo] = {bar: 0, baz: 1, bat: 2} req[:foo] # => "bar, 0, baz, 1, bat, 2" req.get_fields(:foo) # => ["bar", "0", "baz", "1", "bat", "2"]
-
嵌套
req[:foo] = [%w[bar baz], {bat: 0, bam: 1}] req[:foo] # => "bar, baz, bat, 0, bam, 1" req.get_fields(:foo) # => ["bar", "baz", "bat", "0", "bam", "1"] req[:foo] = {bar: %w[baz bat], bam: {bah: 0, bad: 1}} req[:foo] # => "bar, baz, bat, bam, bah, 0, bad, 1" req.get_fields(:foo) # => ["bar", "baz", "bat", "bam", "bah", "0", "bad", "1"]
便捷方法
各种便捷方法用于检索值、设置值、查询值、设置表单值或遍历字段。
Setters
方法 []= 可以设置任何字段,但对新值的验证作用不大;其他一些 setter 方法提供了一些验证。
-
[]=:设置给定键的字符串或数组值。 -
add_field:创建或添加到给定键的值数组。 -
basic_auth:设置'Authorization'的字符串认证头。 -
content_length=:设置字段'Content-Length'的整数长度。 -
content_type=:设置字段'Content-Type'的字符串值。 -
proxy_basic_auth:设置'Proxy-Authorization'的字符串认证头。 -
set_range:设置字段'Range'的值。
表单设置器
-
set_form:设置 HTML 表单数据集合。 -
set_form_data:从 HTML 表单数据设置头字段和正文。
Getters
方法 [] 可以检索任何存在的字段的值,但总是以字符串形式返回;其他一些 getter 方法返回的值与简单字符串值不同。
-
[]:返回给定键的字符串字段值。 -
content_length:返回字段'Content-Length'的整数值,如果不存在则返回nil;请参阅 Content-Length request header。 -
content_range:返回字段'Content-Range'的Range对象值,如果不存在则返回nil。 -
content_type:返回字段'Content-Type'的字符串值,如果不存在则返回nil;请参阅 Content-Type response header。 -
fetch:返回给定键的字符串字段值。 -
get_fields:返回给定key的数组字段值。 -
main_type:返回字段'Content-Type'的字符串值的第一部分(“type”)。 -
sub_type:返回字段'Content-Type'的字符串值的第二部分(“subtype”)。 -
range_length:返回字段'Content-Range'中给定的范围的整数长度。 -
type_params:返回'Content-Type'的字符串参数。
查询
-
chunked?:返回字段'Transfer-Encoding'是否设置为'chunked'。 -
connection_close?:返回字段'Connection'是否设置为'close'。 -
connection_keep_alive?:返回字段'Connection'是否设置为'keep-alive'。 -
key?:返回给定的键是否存在。
Iterators
-
each_capitalized:将每个字段的驼峰命名/值对传递给块。 -
each_capitalized_name:将每个驼峰命名的字段名传递给块。 -
each_header:将每个字段名/值对传递给块。 -
each_name:将每个字段名传递给块。 -
each_value:将每个字符串字段值传递给块。
Constants
Public Instance Methods
Source
# File lib/net/http/header.rb, line 226 def [](key) a = @header[key.downcase.to_s] or return nil a.join(', ') end
Source
# File lib/net/http/header.rb, line 242 def []=(key, val) unless val @header.delete key.downcase.to_s return val end set_field(key, val) end
Source
# File lib/net/http/header.rb, line 263 def add_field(key, val) stringified_downcased_key = key.downcase.to_s if @header.key?(stringified_downcased_key) append_field_value(@header[stringified_downcased_key], val) else set_field(key, val) end end
如果字段存在,则将值 val 添加到字段 key 的值数组中;如果字段不存在,则用给定的 key 和 val 创建该字段。请参阅 Fields。
req = Net::HTTP::Get.new(uri) req.add_field('Foo', 'bar') req['Foo'] # => "bar" req.add_field('Foo', 'baz') req['Foo'] # => "bar, baz" req.add_field('Foo', %w[baz bam]) req['Foo'] # => "bar, baz, baz, bam" req.get_fields('Foo') # => ["bar", "baz", "baz", "bam"]
Source
# File lib/net/http/header.rb, line 949 def basic_auth(account, password) @header['authorization'] = [basic_encode(account, password)] end
使用给定的 account 和 password 字符串设置 'Authorization' 头。
req.basic_auth('my_account', 'my_password') req['Authorization'] # => "Basic bXlfYWNjb3VudDpteV9wYXNzd29yZA=="
Source
# File lib/net/http/header.rb, line 658 def chunked? return false unless @header['transfer-encoding'] field = self['Transfer-Encoding'] (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false end
如果字段 'Transfer-Encoding' 存在且值为 'chunked',则返回 true,否则返回 false;请参阅 Transfer-Encoding response header。
res = Net::HTTP.get_response(hostname, '/todos/1') res['Transfer-Encoding'] # => "chunked" res.chunked? # => true
Source
# File lib/net/http/header.rb, line 970 def connection_close? token = /(?:\A|,)\s*close\s*(?:\z|,)/i @header['connection']&.grep(token) {return true} @header['proxy-connection']&.grep(token) {return true} false end
返回 HTTP 会话是否应关闭。
Source
# File lib/net/http/header.rb, line 978 def connection_keep_alive? token = /(?:\A|,)\s*keep-alive\s*(?:\z|,)/i @header['connection']&.grep(token) {return true} @header['proxy-connection']&.grep(token) {return true} false end
返回 HTTP 会话是否应保持活动。
Source
# File lib/net/http/header.rb, line 620 def content_length return nil unless key?('Content-Length') len = self['Content-Length'].slice(/\d+/) or raise Net::HTTPHeaderSyntaxError, 'wrong Content-Length format' len.to_i end
返回字段 'Content-Length' 的值作为整数,如果不存在该字段则返回 nil;请参阅 Content-Length request header。
res = Net::HTTP.get_response(hostname, '/nosuch/1') res.content_length # => 2 res = Net::HTTP.get_response(hostname, '/todos/1') res.content_length # => nil
Source
# File lib/net/http/header.rb, line 641 def content_length=(len) unless len @header.delete 'content-length' return nil end @header['content-length'] = [len.to_i.to_s] end
将字段 'Content-Length' 的值设置为给定的数值;请参阅 Content-Length response header。
_uri = uri.dup hostname = _uri.hostname # => "jsonplaceholder.typicode.com" _uri.path = '/posts' # => "/posts" req = Net::HTTP::Post.new(_uri) # => #<Net::HTTP::Post POST> req.body = '{"title": "foo","body": "bar","userId": 1}' req.content_length = req.body.size # => 42 req.content_type = 'application/json' res = Net::HTTP.start(hostname) do |http| http.request(req) end # => #<Net::HTTPCreated 201 Created readbody=true>
Source
# File lib/net/http/header.rb, line 674 def content_range return nil unless @header['content-range'] m = %r<\A\s*(\w+)\s+(\d+)-(\d+)/(\d+|\*)>.match(self['Content-Range']) or raise Net::HTTPHeaderSyntaxError, 'wrong Content-Range format' return unless m[1] == 'bytes' m[2].to_i .. m[3].to_i end
返回一个表示字段 'Content-Range' 值的 Range 对象,如果不存在该字段则返回 nil;请参阅 Content-Range response header。
res = Net::HTTP.get_response(hostname, '/todos/1') res['Content-Range'] # => nil res['Content-Range'] = 'bytes 0-499/1000' res['Content-Range'] # => "bytes 0-499/1000" res.content_range # => 0..499
Source
# File lib/net/http/header.rb, line 705 def content_type main = main_type() return nil unless main sub = sub_type() if sub "#{main}/#{sub}" else main end end
从字段 'Content-Type' 的值中返回 媒体类型,如果不存在该字段则返回 nil;请参阅 Content-Type response header。
res = Net::HTTP.get_response(hostname, '/todos/1') res['content-type'] # => "application/json; charset=utf-8" res.content_type # => "application/json"
Source
# File lib/net/http/header.rb, line 457 def delete(key) @header.delete(key.downcase.to_s) end
删除给定不区分大小写的 key 的头(参见 Fields);返回删除的值,如果不存在该字段则返回 nil。
req = Net::HTTP::Get.new(uri) req.delete('Accept') # => ["*/*"] req.delete('Nosuch') # => nil
Source
# File lib/net/http/header.rb, line 488 def each_capitalized block_given? or return enum_for(__method__) { @header.size } @header.each do |k,v| yield capitalize(k), v.join(', ') end end
类似于 each_header,但键以驼峰形式返回。
Net::HTTPHeader#canonical_each 是 Net::HTTPHeader#each_capitalized 的别名。
Source
# File lib/net/http/header.rb, line 421 def each_capitalized_name #:yield: +key+ block_given? or return enum_for(__method__) { @header.size } @header.each_key do |k| yield capitalize(k) end end
将每个驼峰命名的字段名传递给块。
res = Net::HTTP.get_response(hostname, '/todos/1') res.each_capitalized_name do |key| p key if key.start_with?('C') end
输出
"Content-Type" "Connection" "Cache-Control" "Cf-Cache-Status" "Cf-Ray"
驼峰命名取决于系统;请参阅 Case Mapping。
如果未提供块,则返回一个枚举器。
Source
# File lib/net/http/header.rb, line 368 def each_header #:yield: +key+, +value+ block_given? or return enum_for(__method__) { @header.size } @header.each do |k,va| yield k, va.join(', ') end end
将每个键/值对传递给块。
res = Net::HTTP.get_response(hostname, '/todos/1') res.each_header do |key, value| p [key, value] if key.start_with?('c') end
输出
["content-type", "application/json; charset=utf-8"] ["connection", "keep-alive"] ["cache-control", "max-age=43200"] ["cf-cache-status", "HIT"] ["cf-ray", "771d17e9bc542cf5-ORD"]
如果未提供块,则返回一个枚举器。
Source
# File lib/net/http/header.rb, line 395 def each_name(&block) #:yield: +key+ block_given? or return enum_for(__method__) { @header.size } @header.each_key(&block) end
将每个字段键传递给块。
res = Net::HTTP.get_response(hostname, '/todos/1') res.each_key do |key| p key if key.start_with?('c') end
输出
"content-type" "connection" "cache-control" "cf-cache-status" "cf-ray"
如果未提供块,则返回一个枚举器。
Source
# File lib/net/http/header.rb, line 442 def each_value #:yield: +value+ block_given? or return enum_for(__method__) { @header.size } @header.each_value do |va| yield va.join(', ') end end
将每个字符串字段值传递给块。
res = Net::HTTP.get_response(hostname, '/todos/1') res.each_value do |value| p value if value.start_with?('c') end
输出
"chunked" "cf-q-config;dur=6.0000002122251e-06" "cloudflare"
如果未提供块,则返回一个枚举器。
Source
# File lib/net/http/header.rb, line 345 def fetch(key, *args, &block) #:yield: +key+ a = @header.fetch(key.downcase.to_s, *args, &block) a.kind_of?(Array) ? a.join(', ') : a end
使用块时,返回 key 的字符串值(如果存在);否则返回块的值;忽略 default_val;请参阅 Fields。
res = Net::HTTP.get_response(hostname, '/todos/1') # Field exists; block not called. res.fetch('Connection') do |value| fail 'Cannot happen' end # => "keep-alive" # Field does not exist; block called. res.fetch('Nosuch') do |value| value.downcase end # => "nosuch"
不带块时,返回 key 的字符串值(如果存在);否则,如果提供了 default_val,则返回 default_val;否则引发异常。
res.fetch('Connection', 'Foo') # => "keep-alive" res.fetch('Nosuch', 'Foo') # => "Foo" res.fetch('Nosuch') # Raises KeyError.
Source
# File lib/net/http/header.rb, line 310 def get_fields(key) stringified_downcased_key = key.downcase.to_s return nil unless @header[stringified_downcased_key] @header[stringified_downcased_key].dup end
返回给定 key 的数组字段值,如果不存在该字段则返回 nil;请参阅 Fields。
res = Net::HTTP.get_response(hostname, '/todos/1') res.get_fields('Connection') # => ["keep-alive"] res.get_fields('Nosuch') # => nil
Source
# File lib/net/http/header.rb, line 467 def key?(key) @header.key?(key.downcase.to_s) end
如果存在不区分大小写的 key 的字段,则返回 true,否则返回 false。
req = Net::HTTP::Get.new(uri) req.key?('Accept') # => true req.key?('Nosuch') # => false
Source
# File lib/net/http/header.rb, line 727 def main_type return nil unless @header['content-type'] self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip end
从字段 'Content-Type' 的值中返回 媒体类型的开头(“type”)部分,如果不存在该字段则返回 nil;请参阅 Content-Type response header。
res = Net::HTTP.get_response(hostname, '/todos/1') res['content-type'] # => "application/json; charset=utf-8" res.main_type # => "application"
Source
# File lib/net/http/header.rb, line 960 def proxy_basic_auth(account, password) @header['proxy-authorization'] = [basic_encode(account, password)] end
使用给定的 account 和 password 字符串设置 'Proxy-Authorization' 头。
req.proxy_basic_auth('my_account', 'my_password') req['Proxy-Authorization'] # => "Basic bXlfYWNjb3VudDpteV9wYXNzd29yZA=="
Source
# File lib/net/http/header.rb, line 513 def range return nil unless @header['range'] value = self['Range'] # byte-range-set = *( "," OWS ) ( byte-range-spec / suffix-byte-range-spec ) # *( OWS "," [ OWS ( byte-range-spec / suffix-byte-range-spec ) ] ) # corrected collected ABNF # http://tools.ietf.org/html/draft-ietf-httpbis-p5-range-19#section-5.4.1 # http://tools.ietf.org/html/draft-ietf-httpbis-p5-range-19#appendix-C # http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-19#section-3.2.5 unless /\Abytes=((?:,[ \t]*)*(?:\d+-\d*|-\d+)(?:[ \t]*,(?:[ \t]*\d+-\d*|-\d+)?)*)\z/ =~ value raise Net::HTTPHeaderSyntaxError, "invalid syntax for byte-ranges-specifier: '#{value}'" end byte_range_set = $1 result = byte_range_set.split(/,/).map {|spec| m = /(\d+)?\s*-\s*(\d+)?/i.match(spec) or raise Net::HTTPHeaderSyntaxError, "invalid byte-range-spec: '#{spec}'" d1 = m[1].to_i d2 = m[2].to_i if m[1] and m[2] if d1 > d2 raise Net::HTTPHeaderSyntaxError, "last-byte-pos MUST greater than or equal to first-byte-pos but '#{spec}'" end d1..d2 elsif m[1] d1..-1 elsif m[2] -d2..-1 else raise Net::HTTPHeaderSyntaxError, 'range is not specified' end } # if result.empty? # byte-range-set must include at least one byte-range-spec or suffix-byte-range-spec # but above regexp already denies it. if result.size == 1 && result[0].begin == 0 && result[0].end == -1 raise Net::HTTPHeaderSyntaxError, 'only one suffix-byte-range-spec with zero suffix-length' end result end
返回一个表示字段 'Range' 值的 Range 对象数组,如果不存在该字段则返回 nil;请参阅 Range request header。
req = Net::HTTP::Get.new(uri) req['Range'] = 'bytes=0-99,200-299,400-499' req.range # => [0..99, 200..299, 400..499] req.delete('Range') req.range # # => nil
Source
# File lib/net/http/header.rb, line 691 def range_length r = content_range() or return nil r.end - r.begin + 1 end
返回表示字段 'Content-Range' 中给定范围的长度的整数,如果不存在该字段则返回 nil;请参阅 Content-Range response header。
res = Net::HTTP.get_response(hostname, '/todos/1') res['Content-Range'] # => nil res['Content-Range'] = 'bytes 0-499/1000' res.range_length # => 500
Source
# File lib/net/http/header.rb, line 776 def set_content_type(type, params = {}) @header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')] end
设置字段 'Content-Type' 的值;返回新值;请参阅 Content-Type request header。
req = Net::HTTP::Get.new(uri) req.set_content_type('application/json') # => ["application/json"]
Net::HTTPHeader#content_type= 是 Net::HTTPHeader#set_content_type 的别名。
Source
# File lib/net/http/header.rb, line 928 def set_form(params, enctype='application/x-www-form-urlencoded', formopt={}) @body_data = params @body = nil @body_stream = nil @form_option = formopt case enctype when /\Aapplication\/x-www-form-urlencoded\z/i, /\Amultipart\/form-data\z/i self.content_type = enctype else raise ArgumentError, "invalid enctype: #{enctype}" end end
存储将用于 POST 或 PUT 请求的表单数据。
params 中给定的表单数据由零个或多个字段组成;每个字段是
-
一个标量值。
-
一个名称/值对。
-
一个用于读取的
IO流。
参数 params 应为一个 Enumerable(将调用 params.map 方法),通常是数组或哈希。
首先,我们设置一个请求
_uri = uri.dup _uri.path ='/posts' req = Net::HTTP::Post.new(_uri)
参数 params 作为数组
当 params 是一个数组时,它的每个元素都是一个定义字段的子数组;该子数组可以包含
-
一个字符串
req.set_form([['foo'], ['bar'], ['baz']])
-
两个字符串
req.set_form([%w[foo 0], %w[bar 1], %w[baz 2]])
-
当参数
enctype(见下文)被指定为'multipart/form-data'时
各种形式可以混合使用。
req.set_form(['foo', %w[bar 1], ['file', file]])
参数 params 作为哈希
当 params 是一个哈希时,它的每个条目都是一个定义字段的名称/值对。
-
名称是字符串。
-
值可以是
-
nil. -
另一个字符串。
-
一个用于读取的
IO流(仅当参数enctype(见下文)指定为'multipart/form-data'时)。
-
示例
# Nil-valued fields. req.set_form({'foo' => nil, 'bar' => nil, 'baz' => nil}) # String-valued fields. req.set_form({'foo' => 0, 'bar' => 1, 'baz' => 2}) # IO-valued field. require 'stringio' req.set_form({'file' => StringIO.new('Ruby is cool.')}) # Mixture of fields. req.set_form({'foo' => nil, 'bar' => 1, 'file' => file})
可选参数 enctype 指定字段 'Content-Type' 的值,并且必须是以下之一:
-
'application/x-www-form-urlencoded'(默认)。 -
'multipart/form-data';请参阅 RFC 7578。
可选参数 formopt 是一个选项哈希(仅当参数 enctype 为 'multipart/form-data' 时适用),可能包含以下条目:
-
:boundary:值是 multipart 消息的边界字符串。如果未给出,边界是随机字符串。请参阅 Boundary。 -
:charset:值是表单提交的字符集。非文件字段的字段名和值应使用此字符集进行编码。
Source
# File lib/net/http/header.rb, line 816 def set_form_data(params, sep = '&') query = URI.encode_www_form(params) query.gsub!(/&/, sep) if sep != '&' self.body = query self.content_type = 'application/x-www-form-urlencoded' end
将请求正文设置为从参数 params 派生的 URL 编码字符串,并将请求头字段 'Content-Type' 设置为 'application/x-www-form-urlencoded'。
生成的请求适用于 HTTP 请求 POST 或 PUT。
参数 params 必须适用于用作 URI.encode_www_form 的参数 enum。
仅给定参数 params 时,将正文设置为带有默认分隔符 '&' 的 URL 编码字符串。
req = Net::HTTP::Post.new('example.com') req.set_form_data(q: 'ruby', lang: 'en') req.body # => "q=ruby&lang=en" req['Content-Type'] # => "application/x-www-form-urlencoded" req.set_form_data([['q', 'ruby'], ['lang', 'en']]) req.body # => "q=ruby&lang=en" req.set_form_data(q: ['ruby', 'perl'], lang: 'en') req.body # => "q=ruby&q=perl&lang=en" req.set_form_data([['q', 'ruby'], ['q', 'perl'], ['lang', 'en']]) req.body # => "q=ruby&q=perl&lang=en"
还给定时字符串参数 sep,则使用该字符串作为分隔符。
req.set_form_data({q: 'ruby', lang: 'en'}, '|') req.body # => "q=ruby|lang=en"
Net::HTTPHeader#form_data= 是 Net::HTTPHeader#set_form_data 的别名。
Source
# File lib/net/http/header.rb, line 580 def set_range(r, e = nil) unless r @header.delete 'range' return r end r = (r...r+e) if e case r when Numeric n = r.to_i rangestr = (n > 0 ? "0-#{n-1}" : "-#{-n}") when Range first = r.first last = r.end last -= 1 if r.exclude_end? if last == -1 rangestr = (first > 0 ? "#{first}-" : "-#{-first}") else raise Net::HTTPHeaderSyntaxError, 'range.first is negative' if first < 0 raise Net::HTTPHeaderSyntaxError, 'range.last is negative' if last < 0 raise Net::HTTPHeaderSyntaxError, 'must be .first < .last' if first > last rangestr = "#{first}-#{last}" end else raise TypeError, 'Range/Integer is required' end @header['range'] = ["bytes=#{rangestr}"] r end
设置字段 'Range' 的值;请参阅 Range request header。
使用参数 length
req = Net::HTTP::Get.new(uri) req.set_range(100) # => 100 req['Range'] # => "bytes=0-99"
使用参数 offset 和 length
req.set_range(100, 100) # => 100...200 req['Range'] # => "bytes=100-199"
使用参数 range
req.set_range(100..199) # => 100..199 req['Range'] # => "bytes=100-199"
Source
# File lib/net/http/header.rb, line 742 def sub_type return nil unless @header['content-type'] _, sub = *self['Content-Type'].split(';').first.to_s.split('/') return nil unless sub sub.strip end
从字段 'Content-Type' 的值中返回 媒体类型的末尾(“subtype”)部分,如果不存在该字段则返回 nil;请参阅 Content-Type response header。
res = Net::HTTP.get_response(hostname, '/todos/1') res['content-type'] # => "application/json; charset=utf-8" res.sub_type # => "json"
Source
# File lib/net/http/header.rb, line 481 def to_hash @header.dup end
返回键/值对的哈希。
req = Net::HTTP::Get.new(uri) req.to_hash # => {"accept-encoding"=>["gzip;q=1.0,deflate;q=0.6,identity;q=0.3"], "accept"=>["*/*"], "user-agent"=>["Ruby"], "host"=>["jsonplaceholder.typicode.com"]}
Source
# File lib/net/http/header.rb, line 757 def type_params result = {} list = self['Content-Type'].to_s.split(';') list.shift list.each do |param| k, v = *param.split('=', 2) result[k.strip] = v.strip end result end
返回字段 'Content-Type' 值的末尾(“parameters”)部分,如果不存在该字段则返回 nil;请参阅 Content-Type response header。
res = Net::HTTP.get_response(hostname, '/todos/1') res['content-type'] # => "application/json; charset=utf-8" res.type_params # => {"charset"=>"utf-8"}