Files
cpp-httplib/docs-src/pages/ja/cookbook/c04-follow-location.md
2026-04-10 18:16:02 -04:00

39 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: "C04. リダイレクトを追従する"
order: 4
status: "draft"
---
cpp-httplibはデフォルトではリダイレクトHTTP 3xxを追従しません。サーバーから`302 Found`が返ってきても、そのままステータスコード302のレスポンスとして受け取ります。
自動で追従してほしいときは、`set_follow_location(true)`を呼びましょう。
## リダイレクトを追従する
```cpp
httplib::Client cli("http://example.com");
cli.set_follow_location(true);
auto res = cli.Get("/old-path");
if (res && res->status == 200) {
std::cout << res->body << std::endl;
}
```
`set_follow_location(true)`を設定すると、`Location`ヘッダーを見て新しいURLに自動でリクエストを投げ直します。最終的なレスポンスが`res`に入ります。
## HTTPからHTTPSへのリダイレクト
```cpp
httplib::Client cli("http://example.com");
cli.set_follow_location(true);
auto res = cli.Get("/");
```
多くのサイトはHTTPアクセスをHTTPSへリダイレクトします。`set_follow_location(true)`を有効にしておけば、こうしたケースも透過的に扱えます。スキームやホストが変わっても自動で追従します。
> **Warning:** HTTPSへのリダイレクトを追従するには、cpp-httplibをOpenSSLまたは他のTLSバックエンド付きでビルドしておく必要があります。TLSサポートがないと、HTTPSへのリダイレクトは失敗します。
> **Note:** リダイレクトを追従すると、リクエストの実行時間は伸びます。タイムアウトの設定はC12. タイムアウトを設定するを参照してください。