update Readme

This commit is contained in:
2025-09-08 12:51:00 +08:00
parent 2f21d8b948
commit d5250fff74

View File

@@ -34,3 +34,77 @@ c/c++基本开发库
支持格式化输出
# Http请求
提供基于 `cpp-httplib` 的简易 HTTP 客户端封装 `NetRequest`,支持:
1. 同步/异步 GET、POSTJSON、表单
2. 连接/读写超时设置、Keep-Alive
3. 并发请求上限控制
4. 可选内存缓存GET 命中时不发起网络请求)
5. 简单日志回调与性能统计
6. 断点续传下载到本地文件
使用步骤:
1) 引入头文件,配置目标地址
```cpp
#include "NetRequest.hpp"
ntq::RequestOptions opt;
opt.scheme = "http"; // 或 https
opt.host = "127.0.0.1"; // 服务器地址
opt.port = 8080; // 端口https 一般 443
opt.base_path = "/api"; // 可选统一前缀
opt.connect_timeout_ms = 3000;
opt.read_timeout_ms = 8000;
opt.write_timeout_ms = 8000;
opt.default_headers = { {"Authorization", "Bearer TOKEN"} }; // 可选
ntq::NetRequest req(opt);
req.setMaxConcurrentRequests(4);
req.enableCache(std::chrono::seconds(10));
```
2) 发送 GET 请求
```cpp
auto r = req.Get("/info");
if (r && r->status == 200) {
// r->body 为返回内容
}
// 带查询参数与额外请求头
httplib::Params q = {{"q","hello"},{"page","1"}};
httplib::Headers h = {{"X-Req-Id","123"}};
auto r2 = req.Get("/search", q, h);
```
3) 发送 POST 请求
```cpp
// JSONContent-Type: application/json
std::string json = R"({"name":"orangepi","mode":"demo"})";
auto p1 = req.PostJson("/set", json);
// 表单application/x-www-form-urlencoded
httplib::Params form = {{"user","abc"},{"pwd","123"}};
auto p2 = req.PostForm("/login", form);
```
4) 异步调用
```cpp
auto fut = req.GetAsync("/info");
auto res = fut.get(); // 与同步用法一致
```
5) 下载到本地(支持断点续传)
```cpp
bool ok = req.DownloadToFile("/files/pkg.bin", "/tmp/pkg.bin", {}, /*resume*/true);
```
6) 统计信息
```cpp
auto s = req.getStats();
// s.total_requests / s.total_errors / s.last_latency_ms / s.avg_latency_ms
```
说明:
- 若使用 HTTPS需在编译时添加 `-DCPPHTTPLIB_OPENSSL_SUPPORT` 并链接 `-lssl -lcrypto`,且将 `opt.scheme` 设为 `"https"`、端口通常为 `443`
- `base_path` 与各函数传入的 `path` 会自动合并,例如 `base_path="/api"``Get("/info")` 实际请求路径为 `/api/info`