Set-Cookie 字段。Cookie 頭。Set-Cookie 格式:SESSIONID=abc123; Path=/; HttpOnly; Secure,可能有多個 Set-Cookie 頭(多 Cookie)。HttpOnly、Secure、SameSite、Expires/Max-Age、Domain、Path 屬性。| 庫 | 語言 | 特點 |
|---|---|---|
| libcurl | C/C++ | 成熟、跨平台、內置 Cookie Jar (CURLOPT_COOKIEJAR/CURLOPT_COOKIEFILE) |
| cpp-httplib | C++11 | 單頭文件、無依賴、支持 Cookie 手動管理 |
| Boost.Beast | C++17 | 標準庫風格、異步、需自行實現 Cookie 存儲 |
CURL *curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/login");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "user=xxx&pass=yyy");
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookies.txt"); // 保存 Cookie 到文件
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt"); // 後續請求讀取
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); // 自動跟隨重定向
curl_easy_perform(curl);
curl_easy_cleanup(curl);
後續請求同樣設置 CURLOPT_COOKIEFILE 即可自動攜帶 Cookie。
使用 Fiddler / Charles / Wireshark 抓包,觀察登錄請求/響應頭中的 Set-Cookie 與後續請求的 Cookie,驗證提取邏輯正確性。