C++中httplib的使用小結(jié)
一、什么是 cpp-httplib?
cpp-httplib 是一個(gè)輕量級(jí)、單頭文件的 C++ HTTP 客戶端/服務(wù)器庫。只需包含一個(gè)頭文件,即可快速搭建 HTTP 服務(wù)或發(fā)起 HTTP 請(qǐng)求,無需依賴復(fù)雜的第三方庫。
核心特性
| 特性 | 說明 |
|---|---|
| 單頭文件 | 僅需 #include <httplib.h>,零依賴(除 SSL 外) |
| 跨平臺(tái) | 支持 Windows、Linux、macOS |
| HTTP/1.1 | 完整支持持久連接、管道化 |
| SSL/TLS | 可選 OpenSSL 或 mbedTLS 支持 HTTPS |
| 文件上傳 | 原生支持 multipart/form-data |
| 正則路由 | 支持正則表達(dá)式匹配 URL 路徑 |
二、如何安裝和引入
1. 獲取源碼
git clone https://github.com/yhirose/cpp-httplib.git
2. 引入項(xiàng)目
cpp-httplib 是header-only庫,只需將 httplib.h 復(fù)制到你的項(xiàng)目目錄:
#include "httplib.h" // 或者 #include <httplib.h>(如果放在系統(tǒng)路徑)
編譯時(shí)記得鏈接線程庫(Linux):
g++ -std=c++17 server.cpp -o server -pthread
三、核心類與接口詳解
3.1 命名空間與基礎(chǔ)類型
namespace httplib
{
// 范圍請(qǐng)求(用于斷點(diǎn)續(xù)傳)
using Range = std::pair<ssize_t, ssize_t>;
using Ranges = std::vector<Range>;
// 表單數(shù)據(jù)(文件上傳用)
struct MultipartFormData
{
std::string name; // 表單字段名
std::string content; // 文件內(nèi)容
std::string filename; // 文件名
std::string content_type;// MIME 類型
};
// 常用容器別名
using MultipartFormDataItems = std::vector<MultipartFormData>;
using Params = std::multimap<std::string, std::string>; // 查詢參數(shù)
using Headers = std::multimap<std::string, std::string>;// HTTP 頭部
} // namespace httplib3.2 Request 結(jié)構(gòu)體:獲取請(qǐng)求信息
當(dāng)客戶端發(fā)起請(qǐng)求時(shí),cpp-httplib 會(huì)將所有信息封裝在 Request 對(duì)象中:
struct Request
{
std::string method; // HTTP 方法:GET/POST/PUT/DELETE 等
std::string path; // 請(qǐng)求路徑(如 /hi)
Headers headers; // 請(qǐng)求頭
std::string body; // 請(qǐng)求體(POST 數(shù)據(jù)等)
Params params; // URL 查詢參數(shù)(?name=zhangsan&age=18)
MultipartFormDataMap files; // 上傳的文件
Ranges ranges; // 范圍請(qǐng)求(斷點(diǎn)續(xù)傳)
Match matches; // 正則路由捕獲組
};常用字段詳解:
| 字段 | 用途 | 示例 |
|---|---|---|
| method | 判斷請(qǐng)求類型 | req.method == "POST" |
| path | 獲取請(qǐng)求路徑 | /api/user/123 |
| params | 獲取 URL 參數(shù) | ?name=zhangsan → req.params["name"] |
| headers | 獲取請(qǐng)求頭 | req.headers["Content-Type"] |
| body | 獲取原始請(qǐng)求體 | JSON 字符串或表單數(shù)據(jù) |
| matches | 正則匹配結(jié)果 | 捕獲 URL 中的動(dòng)態(tài)部分 |
3.3 Response 結(jié)構(gòu)體:構(gòu)建響應(yīng)
struct Response
{
std::string version; // HTTP 版本
int status = -1; // 狀態(tài)碼:200, 404, 500 等
std::string reason; // 狀態(tài)描述
Headers headers; // 響應(yīng)頭
std::string body; // 響應(yīng)體
// 便捷方法
void set_content(const std::string &s, const std::string &content_type);
void set_header(const std::string &key, const std::string &val);
};關(guān)鍵方法說明:
set_content(body, type):設(shè)置響應(yīng)內(nèi)容和 MIME 類型
- "text/html" - HTML 頁面
- "application/json" - JSON 數(shù)據(jù)
- "text/plain" - 純文本
set_header(key, val):添加自定義響應(yīng)頭(如 CORS 支持)
3.4 Server 類:搭建 HTTP 服務(wù)
class Server
{
public:
// 路由注冊(cè):支持 GET/POST/PUT/DELETE/PATCH/OPTIONS
Server& Get(const std::string &pattern, Handler handler);
Server& Post(const std::string &pattern, Handler handler);
Server& Put(const std::string &pattern, Handler handler);
Server& Delete(const std::string &pattern, Handler handler);
// 靜態(tài)文件服務(wù)
bool set_mount_point(const std::string &mount_point,
const std::string &dir,
Headers headers = Headers());
// 啟動(dòng)服務(wù)器
bool listen(const std::string &host, int port);
private:
using Handler = std::function<void(const Request &, Response &)>;
};路由匹配規(guī)則:
- 精確匹配:
"/hi"匹配http://localhost:9000/hi - 正則匹配:
R"(/numbers/(\d+))"匹配/numbers/123并捕獲數(shù)字
3.5 Client 類:發(fā)起 HTTP 請(qǐng)求
class Client
{
public:
explicit Client(const std::string &host, int port);
// GET 請(qǐng)求
Result Get(const std::string &path, const Headers &headers);
Result Get(const std::string &path,
const Params ¶ms,
const Headers &headers,
Progress progress = nullptr);
// POST 請(qǐng)求(多種重載)
Result Post(const std::string &path,
const std::string &body,
const std::string &content_type);
Result Post(const std::string &path, const Params ¶ms);
Result Post(const std::string &path,
const Headers &headers,
const Params ¶ms);
Result Post(const std::string &path,
const MultipartFormDataItems &items); // 文件上傳
// PUT/DELETE
Result Put(const std::string &path, ...);
Result Delete(const std::string &path, ...);
};3.6 Result 類:處理響應(yīng)結(jié)果
class Result {
public:
operator bool() const; // 是否請(qǐng)求成功
const Response& value() const; // 獲取響應(yīng)(可能拋出異常)
const Response& operator*() const; // 解引用訪問
const Response* operator->() const; // 箭頭訪問
// 使用示例:
// auto res = client.Get("/api");
// if (res && res->status == 200) { ... }
};四、示例
4.1 搭建基礎(chǔ) HTTP 服務(wù)器
#include <httplib.h>
#include <iostream>
// 處理函數(shù):打印請(qǐng)求詳情并返回 HTML
void HelloWorld(const httplib::Request &req, httplib::Response &rsp) {
// 打印請(qǐng)求方法
std::cout << "Method: " << req.method << std::endl;
// 打印請(qǐng)求路徑
std::cout << "Path: " << req.path << std::endl;
// 打印請(qǐng)求體
std::cout << "Body: " << req.body << std::endl;
// 遍歷并打印所有請(qǐng)求頭
std::cout << "Headers:" << std::endl;
for (auto &[key, val] : req.headers) {
std::cout << " " << key << " = " << val << std::endl;
}
// 遍歷并打印 URL 查詢參數(shù)
std::cout << "Params:" << std::endl;
for (auto &[key, val] : req.params) {
std::cout << " " << key << " = " << val << std::endl;
}
// 設(shè)置響應(yīng)內(nèi)容
std::string html_body = "<html><body><h1>Hello World</h1></body></html>";
rsp.set_content(html_body, "text/html");
rsp.status = 200; // HTTP OK
}
int main() {
httplib::Server svr;
// 注冊(cè)路由:GET /hi
svr.Get("/hi", HelloWorld);
// 正則路由:匹配 /numbers/123 這樣的路徑
// R"()" 是原始字符串字面量,避免轉(zhuǎn)義
svr.Get(R"(/numbers/(\d+))", [](const httplib::Request &req,
httplib::Response &rsp) {
std::cout << "Matched path: " << req.path << std::endl;
// req.matches[0] 是整個(gè)匹配的字符串(如 /numbers/123)
// req.matches[1] 是第一個(gè)捕獲組(如 123)
std::cout << "Full match: " << req.matches[0] << std::endl;
std::cout << "Captured number: " << req.matches[1] << std::endl;
rsp.set_content("Number received: " + req.matches[1].str(),
"text/plain");
rsp.status = 200;
});
std::cout << "Server starting at http://0.0.0.0:9000" << std::endl;
// 啟動(dòng)服務(wù)器(阻塞調(diào)用)
svr.listen("0.0.0.0", 9000);
return 0;
}測(cè)試命令:
# 基礎(chǔ)請(qǐng)求 curl "http://localhost:9000/hi?name=zhangsan&age=18" # 正則路由 curl "http://localhost:9000/numbers/123456"
4.2 HTTP 客戶端示例
#include <httplib.h>
#include <iostream>
int main()
{
// 創(chuàng)建客戶端,指定服務(wù)器地址和端口
httplib::Client client("192.168.65.128", 9000);
// 設(shè)置請(qǐng)求頭
httplib::Headers headers =
{
{"Connection", "closed"}, // 短連接
{"User-Agent", "cpp-httplib-client"}
};
// 設(shè)置查詢參數(shù)
httplib::Params params =
{
{"name", "lisi"},
{"age", "18"}
};
// 發(fā)起 GET 請(qǐng)求
auto rsp = client.Get("/hi", params, headers);
// 檢查響應(yīng)
if (rsp)
{ // 請(qǐng)求成功(網(wǎng)絡(luò)層)
std::cout << "Status: " << rsp->status << std::endl;
if (rsp->status == 200)
{ // HTTP 成功
std::cout << "Response body:" << std::endl;
std::cout << rsp->body << std::endl;
}
else
{
std::cerr << "HTTP Error: " << rsp->reason << std::endl;
}
}
else
{
std::cerr << "Request failed (network error)" << std::endl;
}
// POST 請(qǐng)求示例(表單數(shù)據(jù))
httplib::Params form_data = {
{"username", "admin"},
{"password", "123456"}
};
auto post_res = client.Post("/login", form_data);
// POST JSON 示例
std::string json = R"({"user":"admin","pass":"secret"})";
auto json_res = client.Post("/api/login", json, "application/json");
return 0;
}五、原理圖
┌─────────┐ GET /hi?name=zhangsan HTTP/1.1
│ Client │ ───────────────────────────────────────?
└─────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Class Server │
│ ┌─────────────────┐ ┌─────────────────────────────────┐ │
│ │ + get_handlers_ │ │ 路由表 │ │
│ │ + post_handlers_│───?├─────────────┬───────────────────┤ │
│ │ + listen(port) │ │ 路徑 │ 回調(diào)函數(shù) │ │
│ └─────────────────┘ │ /hi │ HelloWorld │ │
│ │ │ /numbers/(\d+)│ lambda │ │
│ │ └─────────────┴───────────────────┘ │
│ │ │ │
│ └──────────────────────────┘ │
│ 匹配成功,調(diào)用回調(diào) │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ void HelloWorld(const Request &req, │
│ Response &rsp) { │
│ // 訪問 req.method, req.path │
│ // 訪問 req.params["name"] │
│ // 設(shè)置 rsp.set_content(...) │
│ // 設(shè)置 rsp.status = 200 │
│ } │
└─────────────────────────────────────┘
六、實(shí)踐與注意事項(xiàng)
6.1 線程安全
Server是多線程的,每個(gè)請(qǐng)求在獨(dú)立線程中處理- 不要在處理函數(shù)中使用非線程安全的全局變量,如果一定要用則加鎖保護(hù)
6.2 錯(cuò)誤處理
// 始終檢查 Result 對(duì)象
auto res = client.Get("/api");
if (!res)
{
// 網(wǎng)絡(luò)錯(cuò)誤:連接失敗、超時(shí)等
std::cerr << "Network error" << std::endl;
return;
}
if (res->status != 200)
{
// HTTP 錯(cuò)誤:404, 500 等
std::cerr << "HTTP " << res->status << ": " << res->reason << std::endl;
return;
}6.3 性能優(yōu)化
// 啟用 Keep-Alive(默認(rèn)已啟用)
httplib::Client client("api.example.com", 80);
client.set_keep_alive(true);
// 設(shè)置超時(shí)
client.set_connection_timeout(5); // 連接超時(shí) 5 秒
client.set_read_timeout(10); // 讀取超時(shí) 10 秒6.4 HTTPS 支持
編譯時(shí)鏈接 OpenSSL:
g++:
g++ -std=c++17 server.cpp -o server -pthread -lssl -lcrypto
如果是用CmakeLists,則需要:
#添加CPPHTTPLIB_OPENSSL_SUPPORT target_compile_definitions(testLLM PRIVATE CPPHTTPLIB_OPENSSL_SUPPORT) #鏈接庫 target_link_libraries(OpenSSL::SSL OpenSSL::Crypto)
代碼中使用:
httplib::SSLServer svr("./cert.pem", "./key.pem"); // HTTPS 服務(wù)器
httplib::SSLClient client("https://example.com"); // HTTPS 客戶端到此這篇關(guān)于C++中httplib的使用小結(jié)的文章就介紹到這了,更多相關(guān)C++ httplib使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++ 中類對(duì)象類型的轉(zhuǎn)化的實(shí)例詳解
這篇文章主要介紹了C++ 中類對(duì)象類型的轉(zhuǎn)化的實(shí)例詳解的相關(guān)資料,這里提供實(shí)例幫助大家學(xué)習(xí)理解這部分內(nèi)容,需要的朋友可以參考下2017-08-08
C++模擬實(shí)現(xiàn)stack和Queue的操作示例
這篇文章主要介紹了C++模擬實(shí)現(xiàn)stack和Queue的操作示例,文中通過代碼示例給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-06-06
C++ struct 初始化與賦值的實(shí)現(xiàn)
在C++中初始化和賦值語句是兩種不同的語法結(jié)構(gòu),本文主要介紹了C++ struct 初始化與賦值的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2025-03-03
visual studio 2013中配置opencv圖文教程 Opencv2.4.9安裝配置教程
這篇文章主要為大家詳細(xì)介紹了Opencv2.4.9安裝教程,以及在visualstudio 2013中opencv的配置步驟,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04
C C++算法題解LeetCode1408數(shù)組中的字符串匹配
這篇文章主要為大家介紹了C C++算法題解LeetCode1408數(shù)組中的字符串匹配示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10
QT實(shí)現(xiàn)年會(huì)抽獎(jiǎng)小軟件的示例代碼
本文主要介紹了QT實(shí)現(xiàn)年會(huì)抽獎(jiǎng)小軟件的示例代碼,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01
C++中指向?qū)ο蟮某V羔樑c指向常對(duì)象的指針詳解
如果一個(gè)變量已經(jīng)被聲明成常變量,則只能用指向常變量的指針變量指向它,而不能用一般的(非const型的)指針變量指向它2013-10-10

