Files
cpp-httplib/docs-src/pages/ja/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

2.1 KiB

title, order, status
title order status
C03. デフォルトヘッダーを設定する 3 draft

同じヘッダーを毎回のリクエストに付けたいときは、set_default_headers()を使います。一度設定すれば、そのクライアントから送るすべてのリクエストに自動で付与されます。

基本の使い方

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");

AcceptやUser-Agentのように、APIを呼ぶたびに必要なヘッダーをまとめて登録できます。リクエストごとに指定する手間が省けます。

Bearerトークンを毎回付ける

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");

認証トークンを一度セットしておけば、以降のリクエストで自動的に送られます。複数のエンドポイントを叩くAPIクライアントを書くときに便利です。

Note: set_default_headers()は既存のデフォルトヘッダーを上書きします。あとから1つだけ追加したい場合でも、全体を渡し直してください。

リクエスト単位のヘッダーと組み合わせる

デフォルトヘッダーを設定していても、個別のリクエストで追加のヘッダーを渡せます。

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

リクエスト単位で渡したヘッダーはデフォルトヘッダーに追加され、両方がサーバーに送られます。デフォルトヘッダーと同じ名前のヘッダーを渡した場合は、リクエスト単位のものだけが送られます。

Bearerトークンを使った認証の詳細はC06. BearerトークンでAPIを呼ぶを参照してください。