https://codechina.csdn.net/mrbaolong/cpp-httplib.git
如何使用httplib
发送GET
请求,同时设置请求参数和Headers
,并同时打印请求数据的进度。
Get
请求using Progress =
std::function<bool(uint64_t current, uint64_t total)>;
using ResponseHandler =
std::function<bool(const Response &response)>;
using ContentReceiver =
std::function<bool(const char *data, size_t data_length)>;
Result Get(
const char *path,
const Params ¶ms,
const Headers &headers,
ResponseHandler response_handler,
ContentReceiver content_receiver,
Progress progress = nullptr
);
client.Get(
"/api/Model/GetAllElementsInView", //请求API
params ,//请求参数
headers,//设置请求头
[&](const httplib::Response& response) {},// 消息回复状态函数
[&](const char* data, size_t data_length){},//回复数据处理函数
[&](uint64_t len, uint64_t total) {}//回复数据进度处理函数
);
#include "httplib.h"
#include "rapidjson/document.h"
#include "OperFile.h"
int main()
{
//SPDLOG_LOGGER_ERROR
std::shared_ptr<spdlog::logger> pLogger = spdlog::default_logger();
SPDLOG_LOGGER_INFO(pLogger, "Directories: {} ", H3DMain_DATA_DIR);
const std::filesystem::path RootPath = H3DMain_DATA_DIR;
const std::filesystem::path ElementPath = RootPath / "Elements.json";
const std::filesystem::path MaterialPath = RootPath / "Materials.json";
const std::filesystem::path pngPath = RootPath / "texture";
const std::filesystem::path ctmPath = RootPath / "ctm";
const std::filesystem::path dbName = RootPath / "Test.H3D";
H3DDB::H3DSqliteDB db(pLogger, dbName.string());
httplib::Client cli("http://bimcomposer.probim.cn");
httplib::Headers headers;
headers.insert({"Accept","text/html,application/xhtml+xml,application/xml;"});
headers.insert({"User-Agent","Mozilla/5.0"});
httplib::Params params;
params.insert({"ProjectID","7d96928d-5add-45cb-a139-2c787141e50d"});
params.insert({"ModelID","71684978-dff5-441b-a653-e1b19e02c878" });
params.insert({"VersionNO",""});
params.insert({"ViewID","228874"});
std::string body;
cli.set_keep_alive(true);
///api/Model/GetAllElementsInView
auto result = cli.Get("/api/Model/GetAllElementsInView",params ,headers, [&](const httplib::Response& response) {
if (response.status == 200) {
SPDLOG_LOGGER_INFO(pLogger, "Loading Elements ......");
}
else {
SPDLOG_LOGGER_ERROR(pLogger, "Loading Elements Failed! Status Code:{}.",response.status);
return false;
}
return true; // return 'false' if you want to cancel the request.
}, [&](const char* data, size_t data_length) {
body.append(data, data_length);
return true; // return 'false' if you want to cancel the request.
}, [&](uint64_t len, uint64_t total) {
SPDLOG_LOGGER_INFO(pLogger, " {} / {} bytes = > {} % complete.",
len, total,
(int)(len * 100 / total));
uint64_t per = (int)(len * 100 / total);
if (per >= 100) {
gsl::span<std::byte> data(reinterpret_cast<std::byte*>(body.data()), body.size());
writeFile(ElementPath, data);
}
return true; // return 'false' if you want to cancel the request.
});
return 0;
}
使用CMakeLists.txt
添加预定义宏。
target_compile_definitions(
H3DMain
PRIVATE
H3DMain_DATA_DIR=\"${PROJECT_SOURCE_DIR}/Data\"
)