module Net::HTTPHeader

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.

Request and Response Fields

Headers may be included in:

  • A Net::HTTPRequest object: the object’s headers will be sent with the request. Any fields may be defined in the request; see Setters.

  • A Net::HTTPResponse object: the objects headers are usually those returned from the host. Fields may be retrieved from the object; see Getters and Iterators.

Exactly which fields should be sent or expected depends on the host; see:

About the Examples

Examples here assume that net/http has been required (which also requires uri):

require 'net/http'

Many code examples here use these example websites:

Some examples also assume these variables:

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

So that example requests may be written as:

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

An example that needs a modified URI first duplicates uri, then modifies the duplicate:

_uri = uri.dup
_uri.path = '/todos/1'

Fields

A header field is a key/value pair.

Field Keys

A field key may be:

  • A string: Key 'Accept' is treated as if it were 'Accept'.downcase; i.e., 'accept'.

  • A symbol: Key :Accept is treated as if it were :Accept.to_s.downcase; i.e., 'accept'.

Examples:

req = Net::HTTP::Get.new(uri)
req[:accept]  # => "*/*"
req['Accept'] # => "*/*"
req['ACCEPT'] # => "*/*"

req['accept'] = 'text/html'
req[:accept] = 'text/html'
req['ACCEPT'] = 'text/html'

Field Values

A field value may be returned as an array of strings or as a string:

  • These methods return field values as arrays:

    • get_fields: Returns the array value for the given key, or nil if it does not exist.

    • to_hash: Returns a hash of all header fields: each key is a field name; its value is the array value for the field.

  • These methods return field values as string; the string value for a field is equivalent to self[key.downcase.to_s].join(', ')):

    • []: Returns the string value for the given key, or nil if it does not exist.

    • fetch: Like [], but accepts a default value to be returned if the key does not exist.

The field value may be set:

  • []=: Sets the value for the given key; the given value may be a string, a symbol, an array, or a hash.

  • add_field: Adds a given value to a value for the given key (not overwriting the existing value).

  • delete: Deletes the field for the given key.

Example field values:

  • 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"]
    
  • Simple array:

    req[:foo] = %w[bar baz bat]
    req[:foo]            # => "bar, baz, bat"
    req.get_fields(:foo) # => ["bar", "baz", "bat"]
    
  • Simple hash:

    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"]
    
  • Nested:

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

Convenience Methods

Various convenience methods retrieve values, set values, query values, set form values, or iterate over fields.

Setters

Method []= can set any field, but does little to validate the new value; some of the other setter methods provide some validation:

  • []=: Sets the string or array value for the given key.

  • add_field: Creates or adds to the array value for the given key.

  • basic_auth: Sets the string authorization header for 'Authorization'.

  • content_length=: Sets the integer length for field 'Content-Length.

  • content_type=: Sets the string value for field 'Content-Type'.

  • proxy_basic_auth: Sets the string authorization header for 'Proxy-Authorization'.

  • set_range: Sets the value for field 'Range'.

Form Setters

  • set_form: Sets an HTML form data set.

  • set_form_data: Sets header fields and a body from HTML form data.

Getters

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 given key.

  • content_length: Returns the integer value of field 'Content-Length'.

  • content_range: Returns the Range value of field 'Content-Range'.

  • content_type: Returns the string value of field 'Content-Type'.

  • fetch: Returns the string field value for the given key.

  • get_fields: Returns the array field value for the given key.

  • main_type: Returns first part of the string value of field 'Content-Type'.

  • sub_type: Returns second part of the string value of field 'Content-Type'.

  • range: Returns an array of Range objects of field 'Range', or nil.

  • range_length: Returns the integer length of the range given in field 'Content-Range'.

  • type_params: Returns the string parameters for 'Content-Type'.

Queries

  • chunked?: Returns whether field 'Transfer-Encoding' is set to 'chunked'.

  • connection_close?: Returns whether field 'Connection' is set to 'close'.

  • connection_keep_alive?: Returns whether field 'Connection' is set to 'keep-alive'.

  • key?: Returns whether a given key exists.

Iterators

Ruby Core © 1993–2024 Yukihiro Matsumoto
Licensed under the Ruby License.
Ruby Standard Library © contributors
Licensed under their own licenses.