title: "HTTPS Client"
前章でOpenSSLのセットアップが済んだので、さっそくHTTPSクライアントを使ってみましょう。2章で使った httplib::Client がそのまま使えます。コンストラクタに https:// 付きのURLを渡すだけです。
実在するHTTPSサイトにアクセスしてみましょう。
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "httplib.h"
#include <iostream>
int main() {
httplib::Client cli("https://nghttp2.org");
auto res = cli.Get("/");
if (res) {
std::cout << res->status << std::endl; // 200
std::cout << res->body.substr(0, 100) << std::endl; // HTMLの先頭部分
} else {
std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
}
}
2章では httplib::Client cli("http://localhost:8080") と書きましたよね。スキームを https:// に変えるだけです。Get() や Post() など、2章で学んだAPIはすべてそのまま使えます。
curl https://nghttp2.org/
HTTPSのデフォルトポートは443です。別のポートを使いたい場合は、URLにポートを含めます。
httplib::Client cli("https://localhost:8443");
httplib::Client はHTTPS接続時、デフォルトでサーバー証明書を検証します。信頼できるCA(認証局)が発行した証明書を持つサーバーにしか接続しません。
CA証明書は、macOSならKeychain、LinuxならシステムのCA証明書ストア、WindowsならWindowsの証明書ストアから自動で読み込みます。ほとんどの場合、追加の設定は要りません。
環境によってはシステムのCA証明書が見つからないこともあります。そのときは set_ca_cert_path() でパスを直接指定してください。
httplib::Client cli("https://nghttp2.org");
cli.set_ca_cert_path("/etc/ssl/certs/ca-certificates.crt");
auto res = cli.Get("/");
curl --cacert /etc/ssl/certs/ca-certificates.crt https://nghttp2.org/
開発中、自己署名証明書のサーバーに接続したいときは、検証を無効にできます。
httplib::Client cli("https://localhost:8443");
cli.enable_server_certificate_verification(false);
auto res = cli.Get("/");
curl -k https://localhost:8443/
本番では絶対に無効にしないでください。中間者攻撃のリスクがあります。
HTTPSサイトへのアクセスでは、リダイレクトに遭遇することがよくあります。たとえば http:// から https:// へ、あるいは www なしから www ありへ転送されるケースです。
デフォルトではリダイレクトを追跡しません。リダイレクト先は Location ヘッダーで確認できます。
httplib::Client cli("https://nghttp2.org");
auto res = cli.Get("/httpbin/redirect/3");
if (res) {
std::cout << res->status << std::endl; // 302
std::cout << res->get_header_value("Location") << std::endl;
}
curl https://nghttp2.org/httpbin/redirect/3
set_follow_location(true) を設定すると、リダイレクトを自動で追跡して、最終的なレスポンスを返してくれます。
httplib::Client cli("https://nghttp2.org");
cli.set_follow_location(true);
auto res = cli.Get("/httpbin/redirect/3");
if (res) {
std::cout << res->status << std::endl; // 200(最終的なレスポンス)
}
curl -L https://nghttp2.org/httpbin/redirect/3
HTTPSクライアントの使い方がわかりましたね。次は自分でHTTPSサーバーを立ててみましょう。自己署名証明書の作り方から始めます。
次: HTTPS Server