Headers
The Headers class represents a collection of HTTP request or response header fields.
It is fully compatible with the Fetch API standard but includes additional convenience methods for scripting environments, such as JSON conversion for debugging and serialization.
A Headers object can be used in the following contexts:
- When creating a request via
RequestInit.headers - When reading headers from a
Responseobject - When programmatically modifying header data in a script
Definition
HeadersInit Type
Headers can be initialized using multiple formats:
You can create a Headers object using any of these forms:
Constructor
new Headers(init?: HeadersInit)
Creates a new Headers instance.
You can optionally pass initial header data.
Parameters
Methods
append(name: string, value: string): void
Adds a new value to an existing header field. If the field already exists, the new value is appended instead of replacing the old one.
Example
set(name: string, value: string): void
Sets a header field to a specific value. If the field already exists, it will be overwritten.
Example
get(name: string): string | null
Retrieves the value of a specific header field.
Returns null if the field does not exist.
Example
has(name: string): boolean
Checks whether a specific header field exists.
Example
delete(name: string): void
Removes a specific header field.
Example
forEach(callback: (value: string, name: string) => void): void
Iterates over all header fields and executes the callback for each pair.
Example
keys(): string[]
Returns an array containing all header names.
Note: Header names are case-insensitive and normalized to lowercase.
values(): string[]
Returns an array containing all header values.
entries(): [string, string][]
Returns an array of [name, value] pairs representing all headers.
Example
toJson(): Record<string, string>
Converts the header collection into a plain JSON object for easy serialization and debugging.
Example
Usage Examples
Example 1 — Setting Custom Headers in a Request
Example 2 — Reading Response Headers
Example 3 — Converting to JSON for Logging
Example 4 — Checking for Specific Headers
Relationships with Other Classes
Notes
- Case-insensitivity: Header names are case-insensitive and stored in lowercase form.
- Multi-value headers: Use
append()to add multiple values for the same header (e.g., forAcceptorCookie). - System headers: Certain system-managed headers (e.g.,
Host,Connection) may be ignored or overwritten by the iOS networking stack. - Serialization: The
toJson()method is useful for logging, debugging, or serializing header data.
Summary
The Headers class is a foundational component of the Scripting networking system, providing a consistent and convenient interface for managing HTTP headers.
It enables developers to:
- Add, modify, and remove headers dynamically
- Read and iterate through response headers
- Work with both request and response headers in a unified way
- Output structured header data for logging and debugging
