推荐一个比较好用的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小时前
|
安全 网络协议 算法
【计算机网络】http协议的原理与应用,https是如何保证安全传输的
【计算机网络】http协议的原理与应用,https是如何保证安全传输的
|
2天前
|
中间件 Go API
Golang深入浅出之-Go语言标准库net/http:构建Web服务器
【4月更文挑战第25天】Go语言的`net/http`包是构建高性能Web服务器的核心,提供创建服务器和发起请求的功能。本文讨论了使用中的常见问题和解决方案,包括:使用第三方路由库改进路由设计、引入中间件处理通用逻辑、设置合适的超时和连接管理以防止资源泄露。通过基础服务器和中间件的代码示例,展示了如何有效运用`net/http`包。掌握这些最佳实践,有助于开发出高效、易维护的Web服务。
14 1
|
6天前
|
存储 算法 程序员
C++从入门到精通:2.2.1标准库与STL容器算法深度解析
C++从入门到精通:2.2.1标准库与STL容器算法深度解析
|
6天前
|
JSON 测试技术 API
Python的Api自动化测试使用HTTP客户端库发送请求
【4月更文挑战第18天】在Python中进行HTTP请求和API自动化测试有多个库可选:1) `requests`是最流行的选择,支持多种请求方法和内置JSON解析;2) `http.client`是标准库的一部分,适合需要低级别控制的用户;3) `urllib`提供URL操作,适用于复杂请求;4) `httpx`拥有类似`requests`的API,提供现代特性和异步支持。根据具体需求选择,如多数情况`requests`已足够。
11 3
|
12天前
|
安全 网络安全 数据安全/隐私保护
HTTP代理SSL连接:保障网络安全的重要协议
HTTP代理SSL连接:保障网络安全的重要协议
|
12天前
|
缓存 网络协议
【计算机协议】第一章——HTTP协议详解
【计算机协议】第一章——HTTP协议详解
|
13天前
|
网络协议 Java API
深度剖析:Java网络编程中的TCP/IP与HTTP协议实践
【4月更文挑战第17天】Java网络编程重在TCP/IP和HTTP协议的应用。TCP提供可靠数据传输,通过Socket和ServerSocket实现;HTTP用于Web服务,常借助HttpURLConnection或Apache HttpClient。两者结合,构成网络服务基础。Java有多种高级API和框架(如Netty、Spring Boot)简化开发,助力高效、高并发的网络通信。
|
13天前
|
安全 网络安全 开发工具
对象存储oss使用问题之flutter使用http库进行post请求文件上传返回400如何解决
《对象存储OSS操作报错合集》精选了用户在使用阿里云对象存储服务(OSS)过程中出现的各种常见及疑难报错情况,包括但不限于权限问题、上传下载异常、Bucket配置错误、网络连接问题、跨域资源共享(CORS)设定错误、数据一致性问题以及API调用失败等场景。为用户降低故障排查时间,确保OSS服务的稳定运行与高效利用。
38 1
|
14天前
|
机器学习/深度学习 定位技术 C++
c++中常用库函数
c++中常用库函数
38 0
|
15天前
|
缓存 安全 网络协议
Http协议是什么
【4月更文挑战第12天】HTTP是用于从WWW服务器传输超文本到浏览器的协议,基于TCP/IP,特点包括无连接、无状态、面向对象、无阻塞和可缓存。它的工作原理是客户端发送请求,服务器处理后返回响应。自1989年创建以来,HTTP已发展支持多媒体内容传输,并通过HTTPS提供安全保护。学习更多可参考计算机网络技术文献。
20 6