1.依赖库 cpp-httplib nlohmann-json
在QT Cmake工程中引入vcpkg
参考:https://blog.csdn.net/zdx135/article/details/130640851
修改vcpkg.json
{
“name”: “entension-packages”,
“version-string”: “0.1.0”,
“dependencies”: [
“spdlog”,
“cpp-httplib”,
“nlohmann-json”
]
}
2. 上传数据接口 http://47.116.128.228:10105/monitors
上传文件接口 http://47.116.128.228:10105/monitors/10086/lcr_file
下载文件路径 http://fcs.audfly.tech/storage/lcrs/10086.lcr
上传数据内容
{
“oem_sn”:“123”, //字符串
“spl_value”: 0.1, //float
“datas”:[0.1,0.2] //数组
}
#include <nlohmann/json.hpp>
#include <httplib.h>
using json = nlohmann::json;
std::shared_ptr<httplib::Client> client_ = std::make_shared<httplib::Client>("47.116.128.228", 10105);
json j;
j["oem_sn"] = "123";
j["spl_value"] = 0.1;
json arr = json::array();
arr.push(0.1);
arr.push(0.2);
j["datas"] = arr;
std::string json_str = j.dump();
//上传数据
auto res_data = client_->Post("/monitors", json_str, "application/json");
if(res_data && res_data ->status == 200)
{
std::cout << "数据上传成功" << res_data ->body << std::endl;
}
//上传文件
std::string file_content = ""; //上传文件路径
// 读取上传文件的内容
std::ifstream data_file(file_content, std::ios::binary);
if (data_file.fail()) {
return;
}
std::ostringstream oss;
oss << data_file.rdbuf();
std::string content = oss.str();
data_file.close();
// 设置传输头 lcr_file是key值 最后有postman的上传设置图片方便理解
httplib::MultipartFormDataItems items = {{"lcr_file", content, file_content, "application/octet-stream"}};
client_->set_read_timeout(200);
QString post_des = "/monitors/10086/lcr_file";
httplib::Result res_file = client_->Post(post_des.toStdString().c_str(), items);
if(res_file && res_file ->status == 200)
{
std::cout << "文件上传成功" << res_file ->body << std::endl;
}
//下载文件
std::string download_file_name = ""; //设置下载文件路径
// 开始下载文件
std::string get_url = "/storage/lcrs/10086.lcr";
std::ofstream ofs(download_file_name, std::ios::binary | std::ios::trunc);
httplib::Client cli("http://fcs.audfly.tech");
auto download_res = cli.Get(get_url.c_str(), [&](const char* data, size_t data_length) {
string_view view(data, data_length);
ofs << view;
return true;
});
if (download_res) {
std::cout << "download_res status ==== " << download_res->status << std::endl;
}
ofs.close();