Module: Net::HTTPHeader

Included in:
HTTPGenericRequest, HTTPResponse
Defined in:
lib/net/http.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 Method Summary collapse

Instance Method Details

#[](key) ⇒ Object

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


1447
1448
1449
1450
# File 'lib/net/http.rb', line 1447

def [](key)
  a = @header[key.downcase] or return nil
  a.join(', ')
end

#[]=(key, val) ⇒ Object

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


1453
1454
1455
1456
1457
1458
1459
# File 'lib/net/http.rb', line 1453

def []=(key, val)
  unless val
    @header.delete key.downcase
    return val
  end
  @header[key.downcase] = [val]
end

#add_field(key, val) ⇒ Object

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"]

1476
1477
1478
1479
1480
1481
1482
# File 'lib/net/http.rb', line 1476

def add_field(key, val)
  if @header.key?(key.downcase)
    @header[key.downcase].push val
  else
    @header[key.downcase] = [val]
  end
end

#basic_auth(account, password) ⇒ Object

Set the Authorization: header for "Basic" authorization.


1811
1812
1813
# File 'lib/net/http.rb', line 1811

def basic_auth(, password)
  @header['authorization'] = [basic_encode(, password)]
end

#chunked?Boolean

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.


1672
1673
1674
1675
1676
# File 'lib/net/http.rb', line 1672

def chunked?
  return false unless @header['transfer-encoding']
  field = self['Transfer-Encoding']
  (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false
end

#connection_close?Boolean


1825
1826
1827
1828
# File 'lib/net/http.rb', line 1825

def connection_close?
  tokens(@header['connection']).include?('close') or
  tokens(@header['proxy-connection']).include?('close')
end

#connection_keep_alive?Boolean


1830
1831
1832
1833
# File 'lib/net/http.rb', line 1830

def connection_keep_alive?
  tokens(@header['connection']).include?('keep-alive') or
  tokens(@header['proxy-connection']).include?('keep-alive')
end

#content_lengthObject

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


1653
1654
1655
1656
1657
1658
# File 'lib/net/http.rb', line 1653

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) ⇒ Object


1660
1661
1662
1663
1664
1665
1666
# File 'lib/net/http.rb', line 1660

def content_length=(len)
  unless len
    @header.delete 'content-length'
    return nil
  end
  @header['content-length'] = [len.to_i.to_s]
end

#content_rangeObject

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.


1682
1683
1684
1685
1686
1687
# File 'lib/net/http.rb', line 1682

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
end

#content_typeObject

Returns a content type string such as "text/html". This method returns nil if Content-Type: header field does not exist.


1697
1698
1699
1700
1701
1702
1703
# File 'lib/net/http.rb', line 1697

def content_type
  return nil unless main_type()
  if sub_type()
  then "#{main_type()}/#{sub_type()}"
  else main_type()
  end
end

#delete(key) ⇒ Object

Removes a header field, specified by case-insensitive key.


1557
1558
1559
# File 'lib/net/http.rb', line 1557

def delete(key)
  @header.delete(key.downcase)
end

#each_capitalizedObject 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.


1580
1581
1582
1583
1584
1585
# File 'lib/net/http.rb', line 1580

def each_capitalized
  block_given? or return enum_for(__method__)
  @header.each do |k,v|
    yield capitalize(k), v.join(', ')
  end
end

#each_capitalized_nameObject

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.


1540
1541
1542
1543
1544
1545
# File 'lib/net/http.rb', line 1540

def each_capitalized_name  #:yield: +key+
  block_given? or return enum_for(__method__)
  @header.each_key do |k|
    yield capitalize(k)
  end
end

#each_headerObject Also known as: each

Iterates through the header names and values, passing in the name and value to the code block supplied.

Example:

response.header.each_header {|key,value| puts "#{key} = #{value}" }

1516
1517
1518
1519
1520
1521
# File 'lib/net/http.rb', line 1516

def each_header   #:yield: +key+, +value+
  block_given? or return enum_for(__method__)
  @header.each do |k,va|
    yield k, va.join(', ')
  end
end

#each_name(&block) ⇒ Object Also known as: each_key

Iterates through the header names in the header, passing each header name to the code block.


1527
1528
1529
1530
# File 'lib/net/http.rb', line 1527

def each_name(&block)   #:yield: +key+
  block_given? or return enum_for(__method__)
  @header.each_key(&block)
end

#each_valueObject

Iterates through header values, passing each value to the code block.


1549
1550
1551
1552
1553
1554
# File 'lib/net/http.rb', line 1549

def each_value   #:yield: +value+
  block_given? or return enum_for(__method__)
  @header.each_value do |va|
    yield va.join(', ')
  end
end

#fetch(key, *args, &block) ⇒ Object

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


1504
1505
1506
1507
# File 'lib/net/http.rb', line 1504

def fetch(key, *args, &block)   #:yield: +key+
  a = @header.fetch(key.downcase, *args, &block)
  a.kind_of?(Array) ? a.join(', ') : a
end

#get_fields(key) ⇒ Object

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"

1495
1496
1497
1498
# File 'lib/net/http.rb', line 1495

def get_fields(key)
  return nil unless @header[key.downcase]
  @header[key.downcase].dup
end

#initialize_http_header(initheader) ⇒ Object


1430
1431
1432
1433
1434
1435
1436
1437
# File 'lib/net/http.rb', line 1430

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) ⇒ Boolean

true if key header exists.


1562
1563
1564
# File 'lib/net/http.rb', line 1562

def key?(key)
  @header.key?(key.downcase)
end

#main_typeObject

Returns a content type string such as "text". This method returns nil if Content-Type: header field does not exist.


1707
1708
1709
1710
# File 'lib/net/http.rb', line 1707

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) ⇒ Object

Set Proxy-Authorization: header for "Basic" authorization.


1816
1817
1818
# File 'lib/net/http.rb', line 1816

def proxy_basic_auth(, password)
  @header['proxy-authorization'] = [basic_encode(, password)]
end

#rangeObject

Returns an Array of Range objects which represent the Range: HTTP header field, or nil if there is no such header.


1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
# File 'lib/net/http.rb', line 1596

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_lengthObject

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


1690
1691
1692
1693
# File 'lib/net/http.rb', line 1690

def range_length
  r = content_range() or return nil
  r.end - r.begin + 1
end

#set_content_type(type, params = {}) ⇒ Object Also known as: content_type=

Sets the content type in an HTTP header. The type should be a full HTTP content type, e.g. "text/html". The params are an optional Hash of parameters to add after the content type, e.g. => 'iso-8859-1'


1740
1741
1742
# File 'lib/net/http.rb', line 1740

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

#set_form(params, enctype = 'application/x-www-form-urlencoded', formopt = {}) ⇒ Object

Set a 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. formpot 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


1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
# File 'lib/net/http.rb', line 1796

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 = '&') ⇒ Object 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 = {"q" => "ruby", "lang" => "en"}
http.form_data = {"q" => ["ruby", "perl"], "lang" => "en"}
http.set_form_data({"q" => "ruby", "lang" => "en"}, ';')

1759
1760
1761
1762
1763
1764
# File 'lib/net/http.rb', line 1759

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) ⇒ Object Also known as: range=

Sets the HTTP Range: header. Accepts either a Range object as a single argument, or a beginning index and a length from that index. Example:

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

1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
# File 'lib/net/http.rb', line 1620

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

#sizeObject Also known as: length

:nodoc: obsolete


1439
1440
1441
# File 'lib/net/http.rb', line 1439

def size   #:nodoc: obsolete
  @header.size
end

#sub_typeObject

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


1715
1716
1717
1718
1719
1720
# File 'lib/net/http.rb', line 1715

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_hashObject

Returns a Hash consisting of header names and values. e.g. => "private",

"content-type" => "text/html",
"date" => "Wed, 22 Jun 2005 22:11:50 GMT"

1571
1572
1573
# File 'lib/net/http.rb', line 1571

def to_hash
  @header.dup
end

#type_paramsObject

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'


1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
# File 'lib/net/http.rb', line 1725

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