Module: Net::HTTPHeader
Relationships & Source Files | |
Extension / Inclusion / Inheritance Descendants | |
Included In:
HTTP::Copy,
HTTP::Delete,
HTTP::Get,
HTTP::Head,
HTTP::Lock,
HTTP::Mkcol,
HTTP::Move,
HTTP::Options,
HTTP::Patch,
HTTP::Post,
HTTP::Propfind,
HTTP::Proppatch,
HTTP::Put,
HTTP::Trace,
HTTP::Unlock,
Net::HTTPAccepted,
Net::HTTPBadGateway,
Net::HTTPBadRequest,
Net::HTTPClientError,
Net::HTTPConflict,
Net::HTTPContinue,
Net::HTTPCreated,
Net::HTTPExpectationFailed,
Net::HTTPFailedDependency,
Net::HTTPForbidden,
Net::HTTPFound,
Net::HTTPGatewayTimeOut,
HTTPGenericRequest,
Net::HTTPGone,
Net::HTTPIMUsed,
Net::HTTPInformation,
Net::HTTPInsufficientStorage,
Net::HTTPInternalServerError,
Net::HTTPLengthRequired,
Net::HTTPLocked,
Net::HTTPMethodNotAllowed,
Net::HTTPMovedPermanently,
Net::HTTPMultiStatus,
Net::HTTPMultipleChoices,
Net::HTTPNetworkAuthenticationRequired,
Net::HTTPNoContent,
Net::HTTPNonAuthoritativeInformation,
Net::HTTPNotAcceptable,
Net::HTTPNotFound,
Net::HTTPNotImplemented,
Net::HTTPNotModified,
Net::HTTPOK,
Net::HTTPPartialContent,
Net::HTTPPaymentRequired,
Net::HTTPPermanentRedirect,
Net::HTTPPreconditionFailed,
Net::HTTPPreconditionRequired,
Net::HTTPProxyAuthenticationRequired,
Net::HTTPRedirection,
HTTPRequest,
Net::HTTPRequestEntityTooLarge,
Net::HTTPRequestHeaderFieldsTooLarge,
Net::HTTPRequestTimeOut,
Net::HTTPRequestURITooLong,
Net::HTTPRequestedRangeNotSatisfiable,
Net::HTTPResetContent,
HTTPResponse,
Net::HTTPSeeOther,
Net::HTTPServerError,
Net::HTTPServiceUnavailable,
Net::HTTPSuccess,
Net::HTTPSwitchProtocol,
Net::HTTPTemporaryRedirect,
Net::HTTPTooManyRequests,
Net::HTTPUnauthorized,
Net::HTTPUnavailableForLegalReasons,
Net::HTTPUnknownResponse,
Net::HTTPUnprocessableEntity,
Net::HTTPUnsupportedMediaType,
Net::HTTPUpgradeRequired,
Net::HTTPUseProxy,
Net::HTTPVersionNotSupported
| |
Defined in: | lib/net/http/header.rb |
Overview
The HTTPHeader module defines methods for reading and writing HTTP headers.
It is used as a mixin by other classes, to provide hash-like access to HTTP header values. Unlike raw hash access, HTTPHeader
provides access via case-insensitive keys. It also provides methods for accessing commonly-used HTTP header values in more convenient formats.
Instance Attribute Summary
-
#content_length
rw
Returns an Integer object which represents the HTTP Content-Length: header field, or
nil
if that field was not provided. - #content_length=(len) rw
-
#chunked? ⇒ Boolean
readonly
Returns “true” if the “transfer-encoding” header is present and set to “chunked”.
- #connection_close? ⇒ Boolean readonly
- #connection_keep_alive? ⇒ Boolean readonly
Instance Method Summary
-
#[](key)
Returns the header field corresponding to the case-insensitive key.
-
#[]=(key, val)
Sets the header field corresponding to the case-insensitive key.
-
#add_field(key, val)
- Ruby 1.8.3
Adds a value to a named header field, instead of replacing its value.
-
#basic_auth(account, password)
Set the Authorization: header for “Basic” authorization.
-
#canonical_each
Alias for #each_capitalized.
-
#content_range
Returns a Range object which represents the value of the Content-Range: header field.
-
#content_type
Returns a content type string such as “text/html”.
-
#content_type=(type, params = {})
Alias for #set_content_type.
-
#delete(key)
Removes a header field, specified by case-insensitive key.
-
#each
Alias for #each_header.
-
#each_capitalized
(also: #canonical_each)
As for #each_header, except the keys are provided in capitalized form.
-
#each_capitalized_name
Iterates through the header names in the header, passing capitalized header names to the code block.
-
#each_header
(also: #each)
Iterates through the header names and values, passing in the name and value to the code block supplied.
-
#each_key(&block)
Alias for #each_name.
-
#each_name(&block)
(also: #each_key)
Iterates through the header names in the header, passing each header name to the code block.
-
#each_value
Iterates through header values, passing each value to the code block.
-
#fetch(key, *args, &block)
Returns the header field corresponding to the case-insensitive key.
-
#form_data=(params, sep = '&')
Alias for #set_form_data.
-
#get_fields(key)
- Ruby 1.8.3
Returns an array of header field strings corresponding to the case-insensitive
key
.
- #initialize_http_header(initheader)
-
#key?(key) ⇒ Boolean
true if
key
header exists. -
#main_type
Returns a content type string such as “text”.
-
#proxy_basic_auth(account, password)
Set Proxy-Authorization: header for “Basic” authorization.
-
#range
Returns an Array of Range objects which represent the Range: HTTP header field, or
nil
if there is no such header. -
#range=(r, e = nil)
Alias for #set_range.
-
#range_length
The length of the range represented in Content-Range: header.
-
#set_content_type(type, params = {})
(also: #content_type=)
Sets the content type in an HTTP header.
-
#set_form(params, enctype = 'application/x-www-form-urlencoded', formopt = {})
Set an HTML form data set.
-
#set_form_data(params, sep = '&')
(also: #form_data=)
Set header fields and a body from HTML form data.
-
#set_range(r, e = nil)
(also: #range=)
Sets the HTTP Range: header.
-
#sub_type
Returns a content type string such as “html”.
-
#to_hash
Returns a Hash consisting of header names and array of values.
-
#type_params
Any parameters specified for the content type, returned as a Hash.
- #append_field_value(ary, val) private
- #basic_encode(account, password) private
- #capitalize(name) private
- #set_field(key, val) private
Instance Attribute Details
#chunked? ⇒ Boolean
(readonly)
Returns “true” if the “transfer-encoding” header is present and set to “chunked”. This is an HTTP/1.1 feature, allowing the the content to be sent in “chunks” without at the outset stating the entire content length.
# File 'lib/net/http/header.rb', line 327
def chunked? return false unless @header['transfer-encoding'] field = self['Transfer-Encoding'] (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false end
#connection_close? ⇒ Boolean
(readonly)
[ GitHub ]
# File 'lib/net/http/header.rb', line 480
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
#connection_keep_alive? ⇒ Boolean
(readonly)
[ GitHub ]
# File 'lib/net/http/header.rb', line 487
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
#content_length (rw)
Returns an Integer object which represents the HTTP Content-Length: header field, or nil
if that field was not provided.
# File 'lib/net/http/header.rb', line 308
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=(len) (rw)
[ GitHub ]# File 'lib/net/http/header.rb', line 315
def content_length=(len) unless len @header.delete 'content-length' return nil end @header['content-length'] = [len.to_i.to_s] end
Instance Method Details
#[](key)
Returns the header field corresponding to the case-insensitive key. For example, a key of “Content-Type” might return “text/html”
# File 'lib/net/http/header.rb', line 38
def [](key) a = @header[key.downcase] or return nil a.join(', ') end
#[]=(key, val)
Sets the header field corresponding to the case-insensitive key.
#add_field(key, val)
- Ruby 1.8.3
-
Adds a value to a named header field, instead of replacing its value. Second argument
val
must be a String. See also #[]=, #[] and #get_fields.request.add_field 'X-My-Header', 'a' p request['X-My-Header'] #=> "a" p request.get_fields('X-My-Header') #=> ["a"] request.add_field 'X-My-Header', 'b' p request['X-My-Header'] #=> "a, b" p request.get_fields('X-My-Header') #=> ["a", "b"] request.add_field 'X-My-Header', 'c' p request['X-My-Header'] #=> "a, b, c" p request.get_fields('X-My-Header') #=> ["a", "b", "c"]
# File 'lib/net/http/header.rb', line 67
def add_field(key, val) if @header.key?(key.downcase) append_field_value(@header[key.downcase], val) else set_field(key, val) end end
#append_field_value(ary, val) (private)
[ GitHub ]# File 'lib/net/http/header.rb', line 90
private def append_field_value(ary, val) case val when Enumerable val.each{|x| append_field_value(ary, x)} else val = val.to_s if /[\r\n]/n.match?(val.b) raise ArgumentError, 'header field value cannnot include CR/LF' end ary.push val end end
#basic_auth(account, password)
Set the Authorization: header for “Basic” authorization.
# File 'lib/net/http/header.rb', line 466
def basic_auth(account, password) @header['authorization'] = [basic_encode(account, password)] end
#basic_encode(account, password) (private)
[ GitHub ]# File 'lib/net/http/header.rb', line 475
def basic_encode(account, password) 'Basic ' + ["#{account}:#{password}"].pack('m0') end
#canonical_each
Alias for #each_capitalized.
# File 'lib/net/http/header.rb', line 216
alias canonical_each each_capitalized
#capitalize(name) (private)
[ GitHub ]# File 'lib/net/http/header.rb', line 218
def capitalize(name) name.to_s.split(/-/).map {|s| s.capitalize }.join('-') end
#content_range
Returns a Range object which represents the value of the Content-Range: header field. For a partial entity body, this indicates where this fragment fits inside the full entity body, as range of byte offsets.
# File 'lib/net/http/header.rb', line 337
def content_range return nil unless @header['content-range'] m = %r<bytes\s(\d)-(\d)/(\d|\*)>i.match(self['Content-Range']) or raise Net::HTTPHeaderSyntaxError, 'wrong Content-Range format' m[1].to_i .. m[2].to_i end
#content_type
Returns a content type string such as “text/html”. This method returns nil if Content-Type: header field does not exist.
#content_type=(type, params = {})
Alias for #set_content_type.
# File 'lib/net/http/header.rb', line 399
alias content_type= set_content_type
#delete(key)
Removes a header field, specified by case-insensitive key.
# File 'lib/net/http/header.rb', line 184
def delete(key) @header.delete(key.downcase) end
#each
Alias for #each_header.
# File 'lib/net/http/header.rb', line 144
alias each each_header
#each_capitalized Also known as: #canonical_each
As for #each_header, except the keys are provided in capitalized form.
Note that header names are capitalized systematically; capitalization may not match that used by the remote HTTP server in its response.
Returns an enumerator if no block is given.
# File 'lib/net/http/header.rb', line 209
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_capitalized_name
Iterates through the header names in the header, passing capitalized header names to the code block.
Note that header names are capitalized systematically; capitalization may not match that used by the remote HTTP server in its response.
Returns an enumerator if no block is given.
# File 'lib/net/http/header.rb', line 165
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
#each_header Also known as: #each
Iterates through the header names and values, passing in the name and value to the code block supplied.
Returns an enumerator if no block is given.
Example:
response.header.each_header {|key,value| puts "#{key} = #{value}" }
#each_key(&block)
Alias for #each_name.
# File 'lib/net/http/header.rb', line 155
alias each_key each_name
#each_name(&block) Also known as: #each_key
Iterates through the header names in the header, passing each header name to the code block.
Returns an enumerator if no block is given.
#each_value
Iterates through header values, passing each value to the code block.
Returns an enumerator if no block is given.
# File 'lib/net/http/header.rb', line 176
def each_value #:yield: value block_given? or return enum_for(__method__) { @header.size } @header.each_value do |va| yield va.join(', ') end end
#fetch(key, *args, &block)
Returns the header field corresponding to the case-insensitive key. Returns the default value args
, or the result of the block, or raises an IndexError if there's no header field named key
See Hash#fetch
# File 'lib/net/http/header.rb', line 123
def fetch(key, *args, &block) #:yield: key a = @header.fetch(key.downcase, *args, &block) a.kind_of?(Array) ? a.join(', ') : a end
#form_data=(params, sep = '&')
Alias for #set_form_data.
# File 'lib/net/http/header.rb', line 421
alias form_data= set_form_data
#get_fields(key)
- Ruby 1.8.3
-
Returns an array of header field strings corresponding to the case-insensitive
key
. This method allows you to get duplicated header fields without any processing. See also #[].p response.get_fields('Set-Cookie') #=> ["session=al98axx; expires=Fri, 31-Dec-1999 23:58:23", "query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"] p response['Set-Cookie'] #=> "session=al98axx; expires=Fri, 31-Dec-1999 23:58:23, query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"
# File 'lib/net/http/header.rb', line 114
def get_fields(key) return nil unless @header[key.downcase] @header[key.downcase].dup end
#initialize_http_header(initheader)
[ GitHub ]# File 'lib/net/http/header.rb', line 13
def initialize_http_header(initheader) @header = {} return unless initheader initheader.each do |key, value| warn "net/http: warning: duplicated HTTP header: #{key}" if key?(key) and $VERBOSE if value.nil? warn "net/http: warning: nil HTTP header: #{key}" 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
#key?(key) ⇒ Boolean
true if key
header exists.
# File 'lib/net/http/header.rb', line 189
def key?(key) @header.key?(key.downcase) end
#main_type
Returns a content type string such as “text”. This method returns nil if Content-Type: header field does not exist.
# File 'lib/net/http/header.rb', line 362
def main_type return nil unless @header['content-type'] self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip end
#proxy_basic_auth(account, password)
Set Proxy-Authorization: header for “Basic” authorization.
# File 'lib/net/http/header.rb', line 471
def proxy_basic_auth(account, password) @header['proxy-authorization'] = [basic_encode(account, password)] end
#range
Returns an Array of Range objects which represent the Range: HTTP header field, or nil
if there is no such header.
# File 'lib/net/http/header.rb', line 225
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=(r, e = nil)
Alias for #set_range.
# File 'lib/net/http/header.rb', line 304
alias range= set_range
#range_length
The length of the range represented in Content-Range: header.
# File 'lib/net/http/header.rb', line 345
def range_length r = content_range() or return nil r.end - r.begin + 1 end
#set_content_type(type, params = {}) Also known as: #content_type=
# File 'lib/net/http/header.rb', line 395
def set_content_type(type, params = {}) @header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')] end
#set_field(key, val) (private)
[ GitHub ]# File 'lib/net/http/header.rb', line 75
private def set_field(key, val) case val when Enumerable ary = [] append_field_value(ary, val) @header[key.downcase] = ary else val = val.to_s # for compatibility use to_s instead of to_str if val.b.count("\r\n") > 0 raise ArgumentError, 'header field value cannnot include CR/LF' end @header[key.downcase] = [val] end end
#set_form(params, enctype = 'application/x-www-form-urlencoded', formopt = {})
Set an HTML form data set. params
is the form data set; it is an Array of Arrays or a Hash +enctype is the type to encode the form data set. It is application/x-www-form-urlencoded or multipart/form-data. formopt
is an optional hash to specify the detail.
- boundary
-
the boundary of the multipart message
- charset
-
the charset of the message. All names and the values of non-file fields are encoded as the charset.
Each item of params is an array and contains following items:
name
-
the name of the field
value
-
the value of the field, it should be a String or a File
opt
-
an optional hash to specify additional information
Each item is a file field or a normal field. If value
is a File object or the opt
have a filename key, the item is treated as a file field.
If Transfer-Encoding is set as chunked, this send the request in chunked encoding. Because chunked encoding is HTTP/1.1 feature, you must confirm the server to support HTTP/1.1 before sending it.
Example: http.set_form([[“q”, “ruby”], [“lang”, “en”]])
See also RFC 2388, RFC 2616, HTML 4.01, and HTML5
# File 'lib/net/http/header.rb', line 451
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
#set_form_data(params, sep = '&') Also known as: #form_data=
Set header fields and a body from HTML form data. params
should be an Array of Arrays or a Hash containing HTML form data. Optional argument sep
means data record separator.
Values are URL encoded as necessary and the content-type is set to application/x-www-form-urlencoded
Example: http.form_data = => “ruby”, “lang” => “en”
http.form_data = => [“ruby”, “perl”], “lang” => “en”
http.set_form_data(=> “ruby”, “lang” => “en”
, ';')
# File 'lib/net/http/header.rb', line 414
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
#set_range(r, e = nil) Also known as: #range=
# File 'lib/net/http/header.rb', line 275
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
#sub_type
Returns a content type string such as “html”. This method returns nil if Content-Type: header field does not exist or sub-type is not given (e.g. “Content-Type: text”).
# File 'lib/net/http/header.rb', line 370
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
#to_hash
Returns a Hash consisting of header names and array of values. e.g. => [“private”],
"content-type" => ["text/html"],
"date" => ["Wed, 22 Jun 2005 22:11:50 GMT"]</code>
# File 'lib/net/http/header.rb', line 198
def to_hash @header.dup end
#type_params
Any parameters specified for the content type, returned as a Hash. For example, a header of Content-Type: text/html; charset=EUC-JP would result in type_params returning => 'EUC-JP'
# File 'lib/net/http/header.rb', line 380
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