The HTTPHeader module provides access to HTTP headers.
The module is included in:
The headers are a hash-like collection of key/value pairs called fields.
Headers may be included in:
Exactly which fields should be sent or expected depends on the host; see:
A header field is a key/value pair.
A field key may be:
req = Net::HTTP::Get.new(uri) req[:accept] # => "*/*" req['Accept'] # => "*/*" req['ACCEPT'] # => "*/*" req['accept'] = 'text/html' req[:accept] = 'text/html' req['ACCEPT'] = 'text/html'
A field value may be returned as an array of strings or as a string:
The field value may be set:
Example field values:
req['Accept'] = 'text/html' # => "text/html" req['Accept'] # => "text/html" req.get_fields('Accept') # => ["text/html"]
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"]
Various convenience methods retrieve values, set values, query values, set form values, or iterate over fields.
Method []= can set any field, but does little to validate the new value; some of the other setter methods provide some validation:
Method [] can retrieve the value of any field that exists, but always as a string; some of the other getter methods return something different from the simple string value:
Returns the string field value for the case-insensitive field key , or nil if there is no such key; see Fields:
res = Net::HTTP.get_response(hostname, '/todos/1') res['Connection'] # => "keep-alive" res['Nosuch'] # => nil
Note that some field values may be retrieved via convenience methods; see Getters.
# File net/http/header.rb, line 216 def [](key) a = @header[key.downcase.to_s] or return nil a.join(', ') end[]= (key, val) click to toggle source
Sets the value for the case-insensitive key to val , overwriting the previous value if the field exists; see Fields:
req = Net::HTTP::Get.new(uri) req['Accept'] # => "*/*" req['Accept'] = 'text/html' req['Accept'] # => "text/html"
Note that some field values may be set via convenience methods; see Setters.
# File net/http/header.rb, line 232 def []=(key, val) unless val @header.delete key.downcase.to_s return val end set_field(key, val) endadd_field (key, val) click to toggle source
Adds value val to the value array for field key if the field exists; creates the field with the given key and val if it does not exist. see 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"]
# File net/http/header.rb, line 253 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 endbasic_auth (account, password) click to toggle source
Set the Authorization: header for “Basic” authorization.
# File net/http/header.rb, line 856 def basic_auth(account, password) @header['authorization'] = [basic_encode(account, password)] endcanonical_each () chunked? () click to toggle source
Returns true if field 'Transfer-Encoding' exists and has value 'chunked' , false otherwise; see Transfer-Encoding response header:
res = Net::HTTP.get_response(hostname, '/todos/1') res['Transfer-Encoding'] # => "chunked" res.chunked? # => true
# File net/http/header.rb, line 646 def chunked? return false unless @header['transfer-encoding'] field = self['Transfer-Encoding'] (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false endconnection_close? () click to toggle source
# File net/http/header.rb, line 870 def connection_close? token = /(?:\A|,)\s*close\s*(?:\z|,)/i @header['connection']&.grep(token) return true> @header['proxy-connection']&.grep(token) return true> false endconnection_keep_alive? () click to toggle source
# File net/http/header.rb, line 877 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 endcontent_length () click to toggle source
Returns the value of field 'Content-Length' as an integer, or nil if there is no such field; see 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
# File net/http/header.rb, line 608 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 endcontent_length= (len) click to toggle source
Sets the value of field 'Content-Length' to the given numeric; see Content-Length response header:
_uri = uri.dup hostname = _uri.hostname # => "jsonplaceholder.typicode.com" _uri.path = '/posts' # => "/posts" req = Net::HTTP::Post.new(_uri) # => # req.body = '' req.content_length = req.body.size # => 42 req.content_type = 'application/json' res = Net::HTTP.start(hostname) do |http| http.request(req) end # => #
# File net/http/header.rb, line 629 def content_length=(len) unless len @header.delete 'content-length' return nil end @header['content-length'] = [len.to_i.to_s] endcontent_range () click to toggle source
Returns a Range object representing the value of field 'Content-Range' , or nil if no such field exists; see 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
# File net/http/header.rb, line 662 def content_range return nil unless @header['content-range'] m = %r.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 endcontent_type () click to toggle source
Returns the media type from the value of field 'Content-Type' , or nil if no such field exists; see 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"
# File net/http/header.rb, line 693 def content_type return nil unless main_type() if sub_type() then "#/#" else main_type() end endcontent_type= (type, params = <>) delete (key) click to toggle source
Removes the header for the given case-insensitive key (see Fields); returns the deleted value, or nil if no such field exists:
req = Net::HTTP::Get.new(uri) req.delete('Accept') # => ["*/*"] req.delete('Nosuch') # => nil
# File net/http/header.rb, line 445 def delete(key) @header.delete(key.downcase.to_s) endeach_capitalized () < |capitalize(k), join(', ')| . >click to toggle source
Like each_header , but the keys are returned in capitalized form.
# File net/http/header.rb, line 476 def each_capitalized block_given? or return enum_for(__method__) < @header.size > @header.each do |k,v| yield capitalize(k), v.join(', ') end endAlso aliased as: canonical_each each_capitalized_name () < |key| . >click to toggle source
Calls the block with each capitalized field name:
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"
The capitalization is system-dependent; see Case Mapping.
Returns an enumerator if no block is given.
# File net/http/header.rb, line 409 def each_capitalized_name #:yield: +key+ block_given? or return enum_for(__method__) < @header.size > @header.each_key do |k| yield capitalize(k) end endeach_header () < |key| . >click to toggle source
Calls the block with each key/value pair:
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"]
Returns an enumerator if no block is given.
# File net/http/header.rb, line 356 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 endAlso aliased as: each each_name () < |key| . >click to toggle source
Calls the block with each field key:
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"
Returns an enumerator if no block is given.
# File net/http/header.rb, line 383 def each_name(&block) #:yield: +key+ block_given? or return enum_for(__method__) < @header.size > @header.each_key(&block) endAlso aliased as: each_key each_value () < |value| . >click to toggle source
Calls the block with each string field value:
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"
Returns an enumerator if no block is given.
# File net/http/header.rb, line 430 def each_value #:yield: +value+ block_given? or return enum_for(__method__) < @header.size > @header.each_value do |va| yield va.join(', ') end endfetch(key, default_val = nil) <|key| . >→ object click to toggle source fetch(key, default_val = nil) → value or default_val
With a block, returns the string value for key if it exists; otherwise returns the value of the block; ignores the default_val ; see 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"
With no block, returns the string value for key if it exists; otherwise, returns default_val if it was given; otherwise raises an exception:
res.fetch('Connection', 'Foo') # => "keep-alive" res.fetch('Nosuch', 'Foo') # => "Foo" res.fetch('Nosuch') # Raises KeyError.
# File net/http/header.rb, line 333 def fetch(key, *args, &block) #:yield: +key+ a = @header.fetch(key.downcase.to_s, *args, &block) a.kind_of?(Array) ? a.join(', ') : a endform_data= (params, sep = '&') get_fields (key) click to toggle source
Returns the array field value for the given key , or nil if there is no such field; see Fields:
res = Net::HTTP.get_response(hostname, '/todos/1') res.get_fields('Connection') # => ["keep-alive"] res.get_fields('Nosuch') # => nil
# File net/http/header.rb, line 298 def get_fields(key) stringified_downcased_key = key.downcase.to_s return nil unless @header[stringified_downcased_key] @header[stringified_downcased_key].dup endkey? (key) click to toggle source
Returns true if the field for the case-insensitive key exists, false otherwise:
req = Net::HTTP::Get.new(uri) req.key?('Accept') # => true req.key?('Nosuch') # => false
# File net/http/header.rb, line 455 def key?(key) @header.key?(key.downcase.to_s) endmain_type () click to toggle source
Returns the leading (‘type’) part of the media type from the value of field 'Content-Type' , or nil if no such field exists; see Content-Type response header:
res = Net::HTTP.get_response(hostname, '/todos/1') res['content-type'] # => "application/json; charset=utf-8" res.main_type # => "application"
# File net/http/header.rb, line 711 def main_type return nil unless @header['content-type'] self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip endproxy_basic_auth (account, password) click to toggle source
Set Proxy-Authorization: header for “Basic” authorization.
# File net/http/header.rb, line 861 def proxy_basic_auth(account, password) @header['proxy-authorization'] = [basic_encode(account, password)] endrange () click to toggle source
Returns an array of Range objects that represent the value of field 'Range' , or nil if there is no such field; see 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
# File net/http/header.rb, line 501 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: '#'" 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: '#'" 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 '#'" 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