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:

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:

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:

The field value may be set:

Example field values:

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:

Form Setters

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:

Queries

Iterators