← 返回库列表

🌐 cpp-httplib 使用指南

轻量级 C++ HTTP/HTTPS 库

项目地址:https://github.com/yhirose/cpp-httplib

📖 什么是 cpp-httplib?

cpp-httplib 是一个仅头文件的 C++ HTTP/HTTPS 库,可以快速搭建 HTTP 服务器或发起客户端请求。它简单易用,无需复杂的依赖配置。

🚀 安装方式

下载头文件

# 下载 httplib.h
wget https://raw.githubusercontent.com/yhirose/cpp-httplib/master/httplib.h

# 或使用 vcpkg
vcpkg install cpp-httplib

💡 基础使用

创建简单的 HTTP 服务器

#include <iostream>
#include "httplib.h"

int main() {
    httplib::Server server;

    // 定义 GET 路由
    server.Get("/hi", [](const httplib::Request& req, httplib::Response& res) {
        res.set_content("Hello World!", "text/plain");
    });

    // 定义带参数的 GET 路由
    server.Get(R"(/numbers/(\d+))", [](const httplib::Request& req, httplib::Response& res) {
        auto numbers = req.matches[1];
        res.set_content("Number: " + numbers, "text/plain");
    });

    // 定义 POST 路由
    server.Post("/post", [](const httplib::Request& req, httplib::Response& res) {
        res.set_content(req.body, "text/plain");
    });

    // 监听端口
    server.listen("0.0.0.0", 8080);

    return 0;
}

返回 JSON 响应

#include "httplib.h"
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    httplib::Server server;

    server.Get("/api/data", [](const httplib::Request& req, httplib::Response& res) {
        json data = {
            {"name", "John"},
            {"age", 25},
            {"city", "Beijing"}
        };

        res.set_header("Content-Type", "application/json");
        res.set_content(data.dump(), "application/json");
    });

    server.listen("0.0.0.0", 8080);
    return 0;
}

获取请求参数

server.Get("/search", [](const httplib::Request& req, httplib::Response& res) {
    // 获取查询参数
    auto q = req.get_param_value("q");
    auto page = req.get_param_value("page");

    std::string result = "Search: " + q + ", Page: " + page;
    res.set_content(result, "text/plain");
});

// 获取 Header
server.Get("/info", [](const httplib::Request& req, httplib::Response& res) {
    auto user_agent = req.get_header_value("User-Agent");
    res.set_content("User-Agent: " + user_agent, "text/plain");
});

静态文件服务

httplib::Server server;

// 设置静态文件目录
server.set_mount_point("/public", "./public");

// 设置基础目录
server.set_base_dir("./www");

// 单文件服务
server.Get("/download", [](const httplib::Request& req, httplib::Response& res) {
    auto ret = res.set_file_content("test.pdf", "application/pdf");
    if (!ret) {
        res.set_content("File not found", "text/plain");
        res.status = 404;
    }
});

HTTPS 服务器

#include "httplib.h"

int main() {
    httplib::SSLServer svr("./cert.pem", "./key.pem");

    svr.Get("/secure", [](const httplib::Request& req, httplib::Response& res) {
        res.set_content("Secure Connection!", "text/plain");
    });

    svr.listen("0.0.0.0", 443);
    return 0;
}

HTTP 客户端

#include "httplib.h"
#include <iostream>

int main() {
    httplib::Client client("httpbin.org", 80);

    // GET 请求
    auto res = client.Get("/get");
    if (res && res->status == 200) {
        std::cout << res->body << std::endl;
    }

    // POST 请求
    httplib::Params params{
        {"name", "John"},
        {"age", "25"}
    };
    res = client.Post("/post", params);

    // POST JSON
    res = client.Post("/post", R"({"key":"value"})", "application/json");

    // 带 Headers 的请求
    httplib::Headers headers = {
        {"Authorization", "Bearer token"},
        {"User-Agent", "MyApp"}
    };
    res = client.Get("/headers", headers);

    return 0;
}

HTTPS 客户端

httplib::Client client("https://example.com");

// 忽略 SSL 验证(仅用于测试)
client.enable_server_certificate_verification(false);

auto res = client.Get("/api/data");

文件上传

server.Post("/upload", [](const httplib::Request& req, httplib::Response& res) {
    auto size = req.files.size();
    std::string result = "Uploaded " + std::to_string(size) + " files\n";

    for (const auto& file : req.files) {
        result += file.first + ": " + file.second.filename + "\n";
    }

    res.set_content(result, "text/plain");
});

异常处理

server.set_exception_handler([](const httplib::Request& req, httplib::Response& res, std::exception_ptr eptr) {
    try {
        if (eptr) std::rethrow_exception(eptr);
    } catch (const std::exception& e) {
        res.set_content(e.what(), "text/plain");
        res.status = 500;
    }
});

// 错误处理器
server.set_error_handler([](const httplib::Request& req, httplib::Response& res) {
    auto fmt = "

Error Status: %d

"; char buf[BUFSIZ]; snprintf(buf, sizeof(buf), fmt, res.status); res.set_content(buf, "text/html"); });

🎯 常见路由模式

方法 模式 说明
server.Get() 获取 GET 请求
server.Post() 创建 POST 请求
server.Put() 更新 PUT 请求
server.Delete() 删除 DELETE 请求
server.Patch() 部分更新 PATCH 请求
R"(/path/(\\d+))" 正则路径 支持正则表达式匹配

📚 更多资源