Headers

Headers can be set in two places: on the client, where they apply to every request, or on an individual request.

Default Headers

client::headers() is the set of headers sent with every request. A natural place for things that do not change between requests, such as a User-Agent or an Accept:

client.headers().set(http::field::user_agent, "MyApp/1.0");
client.headers().set(http::field::accept, "application/json");

Per-Request Headers

The builder’s header function sets a header on a single request. It comes in two overloads:

auto r = co_await client.get("https://example.com")
    .header(http::field::accept_language, "en")
    .header("X-Trace-Id", "abc123")
    .send();

Precedence

A header set on the request takes precedence over a default header of the same name on the client:

client.headers().set(http::field::accept, "application/json");

// this one request asks for XML instead
auto r = co_await client.get("https://example.com")
    .header(http::field::accept, "application/xml")
    .send();

Managed Headers

Some headers are managed by the library and derived from other inputs rather than set directly:

Header Source

Content-Type

The request body, though an explicit Content-Type on the request still wins

Content-Length

The request body, when its length is known

Transfer-Encoding

Set to chunked for a request body of unknown length, in place of Content-Length

Host

The request URL

Authorization

Authentication

Cookie

The cookie jar

Accept-Encoding

The compression settings, unless you set it yourself

Next Steps