Module | Net::HTTPHeader
In: | net/http.rb

Header module.

Provides access to @header in the mixed-into class as a hash-like object, except with case-insensitive keys. Also provides methods for accessing commonly-used header values in a more convenient format.

### Methods

[] []= add_field basic_auth canonical_each chunked? content_length content_length= content_range content_type content_type= delete each each_capitalized each_capitalized_name each_header each_key each_name each_value fetch form_data= get_fields initialize_http_header key? main_type proxy_basic_auth range range= range_length set_content_type set_form_data set_range sub_type to_hash type_params

### External Aliases

size | -> | length

### Public Instance methods

[](key)

Returns the header field corresponding to the case-insensitive key. For example, a key of "Content-Type" might return "text/html"

[Source]

    # File net/http.rb, line 1150
        def [](key)
          a = @header[key.downcase] or return nil
          a.join(', ')
        end

[]=(key, val)

Sets the header field corresponding to the case-insensitive key.

[Source]

    # File net/http.rb, line 1156
        def []=(key, val)
          unless val
            @header.delete key.downcase
            return val
          end
          @header[key.downcase] = Array(val).map {|s| s.to_str }
        end

add_field(key, val)

[Ruby 1.8.3] Adds header field instead of replace. 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"]

[Source]

    # File net/http.rb, line 1179
        def add_field(key, val)
          if @header.key?(key.downcase)
            @header[key.downcase].concat Array(val)
          else
            @header[key.downcase] = Array(val).dup
          end
        end

basic_auth(account, password)

Set the Authorization: header for "Basic" authorization.

[Source]

    # File net/http.rb, line 1410
        def basic_auth(account, password)
          @header['authorization'] = [basic_encode(account, password)]
        end

canonical_each()

Alias for each_capitalized

chunked?()

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.

[Source]

    # File net/http.rb, line 1346
        def chunked?
          return false unless @header['transfer-encoding']
          field = self['Transfer-Encoding']
          (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false
        end

content_length()

Returns an Integer object which represents the Content-Length: header field or `nil` if that field is not provided.

[Source]

    # File net/http.rb, line 1327
        def content_length
          return nil unless key?('Content-Length')
          len = self['Content-Length'].slice(/\d+/) or
              raise HTTPHeaderSyntaxError, 'wrong Content-Length format'
          len.to_i
        end

content_length=(len)

[Source]

    # File net/http.rb, line 1334
        def content_length=(len)
          unless len
            @header.delete 'content-length'
            return nil
          end
          @header['content-length'] = [len.to_i.to_s]
        end

content_range()

Returns a Range object which represents Content-Range: header field. This indicates, for a partial entity body, where this fragment fits inside the full entity body, as range of byte offsets.

[Source]

    # File net/http.rb, line 1355
        def content_range
          return nil unless @header['content-range']
          m = %r<bytes\s+(\d+)-(\d+)/(\d+|\*)>i.match(self['Content-Range']) or
              raise HTTPHeaderSyntaxError, 'wrong Content-Range format'
          m[1].to_i .. m[2].to_i + 1
        end

content_type()

[Source]

    # File net/http.rb, line 1368
        def content_type
          "#{main_type()}/#{sub_type()}"
        end

content_type=(type, params = {})

Alias for set_content_type

delete(key)

Removes a header field.

[Source]

    # File net/http.rb, line 1242
        def delete(key)
          @header.delete(key.downcase)
        end

each(

Alias for each_header

each_capitalized() {|capitalize(k), v.join(', ')| ...}

As for each_header, except the keys are provided in capitalized form.

[Source]

    # File net/http.rb, line 1257
        def each_capitalized
          @header.each do |k,v|
            yield capitalize(k), v.join(', ')
          end
        end

each_capitalized_name() {|+key+| ...}

Iterates for each capitalized header names.

[Source]

    # File net/http.rb, line 1228
        def each_capitalized_name(&block)   #:yield: +key+
          @header.each_key do |k|
            yield capitalize(k)
          end
        end

each_header( {|+key+, +value+| ...}

Iterates for each header names and values.

[Source]

    # File net/http.rb, line 1212
        def each_header   #:yield: +key+, +value+
          @header.each do |k,va|
            yield k, va.join(', ')
          end
        end

each_key()

Alias for each_name

each_name() {|+key+| ...}

Iterates for each header names.

[Source]

    # File net/http.rb, line 1221
        def each_name(&block)   #:yield: +key+
          @header.each_key(&block)
        end

each_value( {|+value+| ...}

Iterates for each header values.

[Source]

    # File net/http.rb, line 1235
        def each_value   #:yield: +value+
          @header.each_value do |va|
            yield va.join(', ')
          end
        end

fetch(key, *args) {|+key+| ...}

Returns the header field corresponding to the case-insensitive key. Returns the default value `args`, or the result of the block, or nil, if there’s no header field named key. See Hash#fetch

[Source]

    # File net/http.rb, line 1206
        def fetch(key, *args, &block)   #:yield: +key+
          a = @header.fetch(key.downcase, *args, &block)
          a.join(', ')
        end

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`. 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"

[Source]

    # File net/http.rb, line 1198
        def get_fields(key)
          return nil unless @header[key.downcase]
          @header[key.downcase].dup
        end

initialize_http_header(initheader)

[Source]

    # File net/http.rb, line 1133
        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
            @header[key.downcase] = [value.strip]
          end
        end

key?(key)

true if `key` header exists.

[Source]

    # File net/http.rb, line 1247
        def key?(key)
          @header.key?(key.downcase)
        end

main_type()

[Source]

    # File net/http.rb, line 1372
        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.

[Source]

    # File net/http.rb, line 1415
        def proxy_basic_auth(account, password)
          @header['proxy-authorization'] = [basic_encode(account, password)]
        end

range()

Returns an Array of Range objects which represents Range: header field, or `nil` if there is no such header.

[Source]

    # File net/http.rb, line 1272
        def range
          return nil unless @header['range']
          self['Range'].split(/,/).map {|spec|
            m = /bytes\s*=\s*(\d+)?\s*-\s*(\d+)?/i.match(spec) or
                    raise HTTPHeaderSyntaxError, "wrong Range: #{spec}"
            d1 = m[1].to_i
            d2 = m[2].to_i
            if    m[1] and m[2] then  d1..d2
            elsif m[1]          then  d1..-1
            elsif          m[2] then -d2..-1
            else
              raise HTTPHeaderSyntaxError, 'range is not specified'
            end
          }
        end

range=(r, e = nil)

Alias for set_range

range_length()

The length of the range represented in Content-Range: header.

[Source]

    # File net/http.rb, line 1363
        def range_length
          r = content_range() or return nil
          r.end - r.begin
        end

set_content_type(type, params = {})

[Source]

    # File net/http.rb, line 1391
        def set_content_type(type, params = {})
          @header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')]
        end

set_form_data(params, sep = '&')

[Source]

    # File net/http.rb, line 1397
        def set_form_data(params, sep = '&')
          self.body = params.map {|k,v| "#{urlencode(k.to_s)}=#{urlencode(v.to_s)}" }.join(sep)
          self.content_type = 'application/x-www-form-urlencoded'
        end

set_range(r, e = nil)

Set Range: header from Range (arg r) or beginning index and length from it (arg idx&len).

      req.range = (0..1023)
      req.set_range 0, 1023

[Source]

    # File net/http.rb, line 1294
        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.last
            last -= 1 if r.exclude_end?
            if last == -1
              rangestr = (first > 0 ? "#{first}-" : "-#{-first}")
            else
              raise HTTPHeaderSyntaxError, 'range.first is negative' if first < 0
              raise HTTPHeaderSyntaxError, 'range.last is negative' if last < 0
              raise 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()

[Source]

    # File net/http.rb, line 1377
        def sub_type
          return nil unless @header['content-type']
          self['Content-Type'].split(';').first.to_s.split('/')[1].to_s.strip
        end

to_hash()

Returns a Hash consist of header names and values.

[Source]

    # File net/http.rb, line 1252
        def to_hash
          @header.dup
        end

type_params()

[Source]

    # File net/http.rb, line 1382
        def type_params
          result = {}
          self['Content-Type'].to_s.split(';')[1..-1].each do |param|
            k, v = *param.split('=', 2)
            result[k.strip] = v.strip
          end
          result
        end

[Validate]