推荐一个比较好用的c++版本http协议库-cpp-httplib

简介: 推荐一个比较好用的c++版本http协议库-cpp-httplib

码云地址:https://gitee.com/fensnote/cpp-httplib


如果是使用32位编译器,可能会报错,修改一下地方即可正常编译:


cpp-httplib


(https://ci.appveyor.com/project/yhirose/cpp-httplib)


A C++11 header-only HTTP library.


It’s extremely easy to setup. Just include httplib.h file in your code!


Inspired by Sinatra and express.


Server Example


#include <httplib.h>

int main(void)
{
    using namespace httplib;

    Server svr;

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

    svr.Get(R"(/numbers/(\d+))", [&](const Request& req, Response& res) {
        auto numbers = req.matches[1];
        res.set_content(numbers, "text/plain");
    });

    svr.listen("localhost", 1234);
}


Post, Put, Delete and Options methods are also supported.


Bind a socket to multiple interfaces and any available port

int port = svr.bind_to_any_port("0.0.0.0");
svr.listen_after_bind();


Method Chain

svr.Get("/get", [](const auto& req, auto& res) {
        res.set_content("get", "text/plain");
    })
    .Post("/post", [](const auto& req, auto& res) {
        res.set_content(req.body(), "text/plain");
    })
    .listen("localhost", 1234);


Static File Server

svr.set_base_dir("./www");


Logging

svr.set_logger([](const auto& req, const auto& res) {
    your_logger(req, res);
});


Error Handler

svr.set_error_handler([](const auto& req, auto& res) {
    const char* fmt = "<p>Error Status: <span style='color:red;'>%d</span></p>";
    char buf[BUFSIZ];
    snprintf(buf, sizeof(buf), fmt, res.status);
    res.set_content(buf, "text/html");
});


‘multipart/form-data’ POST data

svr.Post("/multipart", [&](const auto& req, auto& res) {
    auto size = req.files.size();
    auto ret = req.has_file("name1"));
    const auto& file = req.get_file_value("name1");
    // file.filename;
    // file.content_type;
    auto body = req.body.substr(file.offset, file.length));
})


Client Example


GET

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

int main(void)
{
    httplib::Client cli("localhost", 1234);

    auto res = cli.Get("/hi");
    if (res && res->status == 200) {
        std::cout << res->body << std::endl;
    }
}


POST


res = cli.Post("/post", "text", "text/plain");
res = cli.Post("/person", "name=john1&note=coder", "application/x-www-form-urlencoded");


POST with parameters

httplib::Params params;
params.emplace("name", "john");
params.emplace("note", "coder");

auto res = cli.Post("/post", params);


or

httplib::Params params{
  { "name", "john" },
  { "note", "coder" }
};

auto res = cli.Post("/post", params);


PUT

res = cli.Put("/resource/foo", "text", "text/plain");


DELETE

res = cli.Delete("/resource/foo");


OPTIONS

res = cli.Options("*");
res = cli.Options("/resource/foo");


Connection Timeout

httplib::Client cli("localhost", 8080, 5); // timeouts in 5 seconds


With Progress Callback

httplib::Client client(url, port);

// prints: 0 / 000 bytes => 50% complete
std::shared_ptr<httplib::Response> res =
    cli.Get("/", [](uint64_t len, uint64_t total) {
        printf("%lld / %lld bytes => %d%% complete\n",
            len, total,
            (int)((len/total)*100));
        return true; // return 'false' if you want to cancel the request.
    }
);


This feature was contributed by underscorediscovery.


Range

httplib::Client cli("httpbin.org", 80);

// 'Range: bytes=1-10'
httplib::Headers headers = { httplib::make_range_header(1, 10) };

auto res = cli.Get("/range/32", headers);
// res->status should be 206.
// res->body should be "bcdefghijk".


OpenSSL Support


SSL support is available with CPPHTTPLIB_OPENSSL_SUPPORT. libssl and libcrypto should be linked.

#define CPPHTTPLIB_OPENSSL_SUPPORT

SSLServer svr("./cert.pem", "./key.pem");

SSLClient cli("localhost", 8080);


Zlib Support


‘gzip’ compression is available with CPPHTTPLIB_ZLIB_SUPPORT.


The server applies gzip compression to the following MIME type contents:


  • all text types
  • image/svg+xml
  • application/javascript
  • application/json
  • application/xml
  • application/xhtml+xml


NOTE


g++ 4.8 cannot build this library since <regex> in g++4.8 is broken.


License


MIT license (© 2019 Yuji Hirose)

目录
相关文章
|
22天前
|
人工智能 网络协议 Linux
MCP 协议: Streamable HTTP 是最佳选择
随着AI应用变得越来越复杂并被广泛部署,原有的通信机制面临着一系列挑战。近期MCP仓库的PR #206引入了一个全新的Streamable HTTP传输层替代原有的HTTP+SSE传输层。本文将详细分析该协议的技术细节和实际优势。
591 97
|
10天前
|
数据采集 数据可视化 API
QUIC协议优化:HTTP/3环境下的超高速异步抓取方案
本文介绍了一种基于QUIC和HTTP/3的异步爬虫方案,用于抓取知乎热榜数据并生成趋势图。通过HTTPX与aioquic结合实现高性能连接复用,配合代理IP绕过反爬限制,提取标题、热度等信息。利用Python代码示例展示了异步抓取流程,并借助Matplotlib绘制话题热度变化图表。分析显示突发热点生命周期短,而深度话题热度更稳定。此方案可优化内容运营策略,快速捕捉潜在爆款话题。
QUIC协议优化:HTTP/3环境下的超高速异步抓取方案
|
24天前
|
人工智能 Java API
MCP协议重大升级,Spring AI Alibaba联合Higress发布业界首个Streamable HTTP实现方案
本文由Spring AI Alibaba Contributor刘军、张宇撰写,探讨MCP官方引入的全新Streamable HTTP传输层对原有HTTP+SSE机制的重大改进。文章解析Streamable HTTP的设计思想与技术细节,并介绍Spring AI Alibaba开源框架提供的Java实现,包含无状态服务器模式、流式进度反馈模式等多种场景的应用示例。同时,文章还展示了Spring AI Alibaba + Higress的完整可运行示例,分析当前实现限制及未来优化方向,为开发者提供参考。
|
18天前
|
存储 C++
UE5 C++:自定义Http节点获取Header数据
综上,通过为UE5创建一个自定义HTTP请求类并覆盖GetResult方法,就能成功地从HTTP响应的Header数据中提取信息。在项目中使用自定义类,不仅可以方便地访问响应头数据,也可随时使用这些信息。希望这种方法可以为你的开发过程带来便利和效益。
74 35
|
17天前
|
XML JSON 网络协议
利用HTTP POST协议实现简单的RPC协议:WireShark抓包分析
通过这种方式,我们可以使用HTTP POST实现简单的RPC协议,并使用WireShark进行抓包分析。这不仅可以帮助我们理解RPC协议的工作原理,也可以帮助我们调试和优化我们的代码。
74 30
|
12天前
|
JSON 安全 网络协议
HTTP/HTTPS协议(请求响应模型、状态码)
本文简要介绍了HTTP与HTTPS协议的基础知识。HTTP是一种无状态的超文本传输协议,基于TCP/IP,常用80端口,通过请求-响应模型实现客户端与服务器间的通信;HTTPS为HTTP的安全版本,基于SSL/TLS加密技术,使用443端口,确保数据传输的安全性。文中还详细描述了HTTP请求方法(如GET、POST)、请求与响应头字段、状态码分类及意义,并对比了两者在请求-响应模型中的安全性差异。
93 20
|
14天前
|
存储 数据库 Python
使用HTTP POST协议将本地压缩数据发送到服务器
总的来说,使用HTTP POST协议将本地压缩数据发送到服务器是一个涉及多个步骤的过程,包括创建压缩文件,设置HTTP客户端,发送POST请求,以及服务器端的处理。虽然这个过程可能看起来复杂,但一旦你理解了每个步骤,就会变得相对简单。
63 19
|
22天前
|
安全 网络安全 数据安全/隐私保护
HTTP 与 HTTPS 协议及 SSL 证书解析-http和https到底有什么区别?-优雅草卓伊凡
HTTP 与 HTTPS 协议及 SSL 证书解析-http和https到底有什么区别?-优雅草卓伊凡
70 3
|
Web App开发 前端开发

热门文章

最新文章