Files
cpp-httplib/docs-src/pages/ja/cookbook/c15-compression.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.3 KiB

title, order, status
title order status
C15. 圧縮を有効にする 15 draft

cpp-httplibは送信時の圧縮と受信時の解凍をサポートしています。ただし、zlib、Brotli、Zstdのいずれかを有効にしてビルドしておく必要があります。

ビルド時の準備

圧縮機能を使うには、httplib.hをインクルードする前に次のマクロを定義しておきます。

#define CPPHTTPLIB_ZLIB_SUPPORT    // gzip / deflate
#define CPPHTTPLIB_BROTLI_SUPPORT  // brotli
#define CPPHTTPLIB_ZSTD_SUPPORT    // zstd
#include <httplib.h>

有効にした方式に応じて、zlib、brotli、zstdのライブラリもリンクします。

リクエストボディを圧縮して送る

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

std::string big_payload = build_payload();
auto res = cli.Post("/api/data", big_payload, "application/json");

set_compress(true)を呼んでおくと、POST、PUT、PATCHのリクエストボディが圧縮されて送信されます。圧縮方式は、ビルドで有効にしたもののうち、Brotli、gzip、Zstdの順で最初に当てはまるものです。サーバー側もその方式に対応している必要があります。

レスポンスを解凍する

httplib::Client cli("https://api.example.com");
cli.set_decompress(true); // デフォルトで有効

auto res = cli.Get("/api/data");
std::cout << res->body << std::endl;

set_decompress(true)を呼ぶと、サーバーがContent-Encoding: gzipなどで圧縮したレスポンスを自動で解凍してくれます。res->bodyには解凍済みのデータが入ります。

デフォルトで有効なので、通常は何もしなくても解凍されます。あえて生の圧縮データを触りたいときだけset_decompress(false)にしましょう。

Warning: 圧縮ライブラリを1つも有効にしていないビルドでは、set_compress(true)を呼んでもリクエストは圧縮されません。また、ビルドで有効にしていない方式で圧縮されたレスポンスが返ってくると、リクエストはError::UnsupportedContentEncodingで失敗します。うまく動かないときは、まずマクロの定義を確認しましょう。