Files
cpp-httplib/docs-src/pages/en/cookbook/c03-default-headers.md
T
yhirose 9bfd2ddf1c Fix README and docs pages that no longer match the code
Bring the READMEs and the docs pages (en and ja) in line with the
current header:

- Fix the client sample that does not compile, the Transfer-Encoding
  statement for default headers, the verifier callback comment, the
  thread pool spawn rule, the sanitize_filename description, and the
  inverted Accept-Encoding sentence.
- Describe recent behaviour: TLS errors behind Read/Write failures,
  Host validation, Connection: close for a body without length,
  content_reader rules, refused CONNECT, WebSocketClient proxies,
  CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT, the SSE event size limit, and
  the payload limit of the Stream API.
- Complete the API references of WebSocket, WebSocketClient and the
  stream:: helpers, and the SSE reconnect rules.
- Fix cookbook pages: keychain loading on every backend, received Close
  status, a multipart sample that trusted the client's file name, an
  echo sample that sent binary as text, SNI, pre-request handler scope,
  stop() with WebSocket handlers, and the thread pool notes.
- Restore the mutex in the LLM app's Chapter 5 code.
2026-10-18 10:13:57 -04:00

1.6 KiB

title, order, status
title order status
C03. Set Default Headers 3 draft

When you want the same headers on every request, use set_default_headers(). Once set, they're attached automatically to every request sent from that client.

Basic usage

httplib::Client cli("https://api.example.com");

cli.set_default_headers({
  {"Accept", "application/json"},
  {"User-Agent", "my-app/1.0"},
});

auto res = cli.Get("/users");

Register the headers you need on every API call — like Accept or User-Agent — in one place. No need to repeat them on each request.

Send a Bearer token on every request

httplib::Client cli("https://api.example.com");

cli.set_default_headers({
  {"Authorization", "Bearer " + token},
  {"Accept", "application/json"},
});

auto res1 = cli.Get("/me");
auto res2 = cli.Get("/projects");

Set the auth token once, and every subsequent request carries it. Handy when you're writing an API client that hits multiple endpoints.

Note: set_default_headers() replaces the existing default headers. Even if you only want to add one, pass the full set again.

Combine with per-request headers

You can still pass extra headers on individual requests, even with defaults set.

httplib::Headers headers = {
  {"X-Request-ID", "abc-123"},
};
auto res = cli.Get("/users", headers);

Per-request headers are added on top of the defaults, and both are sent to the server. If a per-request header has the same name as a default one, only the per-request one is sent.

For details on Bearer token auth, see C06. Call an API with a Bearer token.