云计算百科
云计算领域专业知识百科平台

cpp-httplib库的接口介绍(服务器接口 -- server类,request类,Response类的部分字段和接口)

目录

cpp-httplib

介绍

下载

服务器接口

Server

Server类

Get()

pattern

handler

Post()

listen()

host

stop()

Request类

字段

get_file_value()

key

返回值

has_param()

key

get_param_value()

key

Response类

字段

set_content()

content

content-type

set_header()

get_header_value()

name


cpp-httplib

介绍

cpp-httplib是一个非常轻量级的 C++ HTTP 库,提供了简单且功能强大的 HTTP/HTTPS 客户端和服务器实现

  • 该库的最大特点是没有依赖其他第三方库,使其非常容易集成和使用 — 在代码中只需要包含头文件"httplib.h所在路径"系统pthread库的头文件即可,不需要在编译语句中指明cpp-httplib
  • 除了支持 HTTPS 时需要 OpenSSL 或 mbedTLS

下载

git clone https://github.com/yhirose/cpp-httplib.git 注意事项

  • 需要使用较新版本的gcc 7以上

如果gcc在7以上,但不是特别新的话

  • 不能使用最新的cpp-httplib,推荐使用0.7.15
  • 在标签中可以选择下载版本

服务器接口

Server

Server类

Server就是服务器中的核心类,构造时不需要传参

  • 用于构建http服务器
  • httplib::Server server;
Get()

用于发起http请求

  • get请求会从服务器请求指定路径的资源

将参数附加在 URL 的查询字符串中

pattern

标识请求的url路径模式

  • 服务器会根据这个模式匹配客户端发来的请求,并将匹配的请求路由到对应的处理函数
handler

处理函数

  • 一般传入lambda表达式
  • 并且可以获取到请求和响应对象,供后续处理
Post()

将数据包含在请求的主体中(Request Body)

  • 所以提取数据时,通过body获取

  • 和get类似
listen()

启动 HTTP 服务器,在指定主机和端口上监听

  • 调用该函数后,服务器会持续运行,直到手动停止或服务器进程崩溃

host

stop()

停止服务器运行

在函数体内,我们可以通过两个对象来获取请求内容和构建响应

Request类

字段

get_file_value()

获取表单上传的文件信息

  • 当客户端以 multipart/form-data 格式上传文件时,可以使用此方法来获取上传的文件

key

要获取的文件字段的名称

返回值

返回与key相关的文件信息

  • 类型为File

svr.Post("/upload", [](const httplib::Request& req, httplib::Response& res) {
// 获取文件
if (req.has_file("file")) {
const httplib::File& file = req.get_file_value("file");
// 处理文件,比如保存文件到服务器
std::ofstream ofs(file.filename, std::ios::binary);
ofs << file.content;
ofs.close();

res.set_content("File uploaded successfully", "text/plain");
} else {
res.set_content("No file uploaded", "text/plain");
}
});

has_param()

检查请求的查询字符串中是否包含特定的参数

key

查询参数的名称

get_param_value()

获取请求的查询字符串中指定参数的值

  • 如果该参数不存在,则返回空字符串
  • 一般与has_param()结合使用

key

查询参数的名称

svr.Post("/submit", [](const httplib::Request& req, httplib::Response& res) {
std::string name = req.get_param_value("name");
if (!name.empty()) {
res.set_content("Received name: " + name, "text/plain");
} else {
res.set_content("No name provided", "text/plain");
}
});

Response类

字段

set_content()

设置响应内容

content

返回给客户端的实际数据内容

content-type

指定响应内容的类型,告诉客户端如何解析和处理返回的数据

set_header()

设置响应头sehzhi

#include <httplib.h>

int main() {
httplib::Server svr;

svr.Get("/api", [](const httplib::Request& req, httplib::Response& res) {
res.set_header("Content-Type", "application/json");
res.set_header("Cache-Control", "no-store");
res.set_header("X-Custom-Header", "CustomValue");

std::string jsonResponse = R"({"message": "Hello, API!"})";
res.set_content(jsonResponse, "application/json");
});

svr.listen("localhost", 8080);
return 0;
}

get_header_value()

获取指定名称的响应头的值

  • 如果不存在则返回空字符串

name

响应头的名称

赞(0)
未经允许不得转载:网硕互联帮助中心 » cpp-httplib库的接口介绍(服务器接口 -- server类,request类,Response类的部分字段和接口)
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!