【C++框架#6】Cpp-httplib 安装与使用

【C++框架#6】Cpp-httplib 安装与使用

📃个人主页:island1314

⛺️ 欢迎关注:👍点赞 👂🏽留言 😍收藏 💞 💞 💞

生活总是不会一帆风顺,前进的道路也不会永远一马平川,如何面对挫折影响人生走向 – 《人民日报》


🔥 目录

cpp-httplib 安装与使用1. 基本概述2. 安装3. 常用接口3.1 客户端接口3.2 服务端接口3.3 文件上传和下载
4. 样例代码


cpp-httplib 安装与使用

1. 基本概述

C++ HTTP 库(cpp-httplib)是一个轻量级的 C++ HTTP 客户端/服务器库,它提供了 简单的 API 来创建 HTTP 服务器和客户端,支持同步和异步操作

以下是一些关于 cpp-httplib 的 主要特点

单文件库
cpp-httplib
是一个单文件头文件库,易于集成到现有项目中。只需将
httplib.h
包含到项目中即可开始使用支持 HTTP 客户端和服务器:它不仅支持作为 HTTP 客户端发送请求,也支持构建 HTTP 服务器处理客户端请求支持 SSL/TLS:通过使用 OpenSSL 或 mbedTLS 库,cpp-httplib 支持 HTTPS 和 WSS易于使用:API 简单直观,适合快速开发和使用异步支持:虽然主要是同步的,但它也支持异步 HTTP 请求依赖性少 简单轻量:该库没有大量外部依赖,使用起来非常轻量适合小型项目:尤其适合嵌入式系统、微服务、以及快速构建 HTTP 服务的场景

主要功能

HTTP 客户端功能:支持发送 GET、POST、PUT、DELETE 等 HTTP 请求,并处理响应数据HTTP 服务器功能:能够快速搭建简单的 HTTP 服务器,处理不同的 HTTP 请求(如 GET、POST、PUT 等)支持 HTTPS:通过集成 OpenSSL 支持安全的 HTTPS 请求多种响应类型:支持返回字符串、文件、JSON 数据等多种类型的响应处理 URL 参数和表单数据:可以轻松处理 GET 请求中的查询参数,POST 请求中的表单数据支持自定义请求头:可以轻松地为请求添加自定义头部

2. 安装


git clone https://github.com/yhirose/cpp-httplib.git

然后把其中的
httplib.h
拷贝出来进行使用,比如


cp httplib.h /home/lighthouse/code/project/chat-client/code/server/common/

3. 常用接口

3.1 客户端接口

httplib::Client(const std::string &host, int port = 80);

GET 请求:获取指定路径的数据


auto res = client.Get("/path");

POST 请求:发送一个POST请求,body是请求体数据,Content-type请求头数据;支持发送JSON、文本等数据


auto res = client.Post("/path", body, "Content-Type: application/json");

PUT 请求:一般用于更新资源


auto res = client.Put("/path", body, "Content-Type: application/json");

DELETE 请求


auto res = client.Delete("/path");

访问响应状态码
int status = res->status;
访问响应体
std::string body = res->body;
访问响应头
std::string content_type = res->get_header_value("Content-Type");

3.2 服务端接口

构造函数


httplib::Server();

定义路由:借助路由方法定义服务器如何处理不同类型的HTTP请求,每一个路由都对应一个HTTP动作

处理 GET 请求


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

处理 POST 请求


svr.Post("/submit", [](const httplib::Request& req, httplib::Response& res) {
    std::string body = req.body;
    res.set_content("POST received!", "text/plain");
});

处理 PUT 请求


svr.Put("/update", [](const httplib::Request& req, httplib::Response& res) {
    res.set_content("PUT request received!", "text/plain");
});

启动服务器


svr.listen("localhost", 8080);

设置响应内容


res.set_content("response body", "text/plain");

获取 URL 路径参数


svr.Get("/users/{id}", [](const httplib::Request& req, httplib::Response& res) {
    std::string id = req.matches[1]; // 获取 URL 中的 id 参数
    res.set_content("User ID: " + id, "text/plain");
});
3.3 文件上传和下载


Multipart form-data
:支持发送和接收 multipart/form-data 类型的请求,这对于 文件上传非常有用

上传文件


std::ifstream file("file.txt", std::ios::binary);
auto res = client.Post("/upload", file, "application/octet-stream");

下载文件


svr.Get("/download", [](const httplib::Request& req, httplib::Response& res) {
    res.set_content_from_file("file.txt", "text/plain");
});

4. 样例代码


// 服务器搭建流程
int main(){
    // 1. 实例化服务器对象 Server
    httplib::Server server;
    // 2. 注册回调函数 -- 告诉服务器收到哪个请求, 用对应回调函数来处理
    server.Get("/hi", [](const httplib::Request& req, httplib::Response &rsp){
        std::cout << "method: " << req.method << ", path: " << req.path << "
";
        for(auto it: req.headers){
            std::cout << it.first << ": " << it.second << "
";
        }
        std::string body = "<html><body><h1>Hello IsLand</h1></body></html>";
        rsp.set_content(body, "text/html");
        rsp.status = 200;
    });
    // server.Post();
    // 3. 启动服务器
    server.listen("0.0.0.0", 9090);
    return 0;
}

结果如下


method: GET, path: /hi
REMOTE_PORT: 11074
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
LOCAL_PORT: 9090
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 SLBrowser/9.0.6.5061 SLBChan/105 SLBVPV/64-bit
REMOTE_ADDR: 111.8.73.163
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
LOCAL_ADDR: 10.0.8.10
Accept-Language: zh-CN,zh;q=0.9
Connection: keep-alive
Host: 1.12.51.69:9090

【C++框架#6】Cpp-httplib 安装与使用

★,°:.☆( ̄▽ ̄)/$:.°★ 】那么本篇到此就结束啦,如果有不懂 和 发现问题的小伙伴可以在评论区说出来哦,同时我还会继续更新关于【】的内容,请持续关注我 !!

【C++框架#6】Cpp-httplib 安装与使用

© 版权声明

相关文章

暂无评论

none
暂无评论...