• http发送和接收图片json文件


     一、http数据发送

    1、先将图片转换为base64格式

    1. std::string detectNet::Mat2Base64(const cv::Mat &image, std::string imgType){
    2. std::vector buf;
    3. cv::imencode(imgType, image, buf);
    4. //uchar *enc_msg = reinterpret_cast(buf.data());
    5. std::string img_data = base64_encode(buf.data(), buf.size(), false);
    6. return img_data;
    7. }

    2、将数据以json格式进行发送

    1. void detectNet::send_json_people(cv::Mat img, std::string label, std::string level, std::string rtsp){
    2. std::string out = Mat2Base64(img,".jpg");
    3. //std::cout << out << std::endl;
    4. ImgInfo imgInfo(out, label, level, rtsp);
    5. static auto client = httplib::Client("127.0.0.1", 18080);
    6. auto result = client.Post("/uploadAlgorithmResult", imgInfo.to_json_people(), "application/json");
    7. if (result != nullptr && result->status == 200) {
    8. std::cout << result->body << std::endl;
    9. }
    10. }

    其中 ImgInfo 类为:

    1. #ifndef HTTP_DEMO_IMGINFO_H
    2. #define HTTP_DEMO_IMGINFO_H
    3. #include
    4. #include "cJSON.h"
    5. #include "base64.h"
    6. #define RTSP_URL "rtsp://admin:a123456789@192.168.8.31:554/h264/ch1/main/av_stream/1"
    7. #define AlgorithmType "hook_detection"
    8. #define AlgorithmType_people "danger_zone"
    9. #define AlgorithmType_crooked "crooked"
    10. class ImgInfo {
    11. private:
    12. std::string img;
    13. std::string label;
    14. std::string rtsp;
    15. std::string level;
    16. public:
    17. ImgInfo(std::string img, std::string label,
    18. std::string level, std::string rtsp) : img(std::move(img)), label(std::move(label)),
    19. level(std::move(level)), rtsp(std::move(rtsp)) {}
    20. std::string to_json_people() {
    21. auto *root = cJSON_CreateObject();
    22. cJSON_AddStringToObject(root, "image", img.c_str());
    23. cJSON_AddStringToObject(root, "level", level.c_str());
    24. cJSON_AddStringToObject(root, "rtsp", rtsp.c_str());
    25. cJSON_AddStringToObject(root, "type", AlgorithmType_people);
    26. cJSON_AddStringToObject(root, "label", label.c_str());
    27. /*
    28. cJSON *label_array = cJSON_CreateArray();
    29. for (auto &i: label) {
    30. cJSON_AddItemToArray(label_array, cJSON_CreateString(i.c_str()));
    31. }
    32. cJSON_AddItemToObject(root, "label", label_array);
    33. */
    34. char *out = cJSON_Print(root);
    35. std::string res = out;
    36. free(out);
    37. cJSON_Delete(root);
    38. return res;
    39. }
    40. };
    41. #endif //HTTP_DEMO_IMGINFO_H

    上述代码中json数据有五个部分:image为图片数据,level是告警等级,rtsp为数据流地址,type是算法类型,label是算法标签等,所以数据发送为这五个内容。

    二、http数据接收

    HttpServer.cpp如下: 

    1. //#include
    2. //#include
    3. #include "HttpServer.h"
    4. #include
    5. #include
    6. //#include "QString"
    7. //#include "TimeUtils.hpp"
    8. //#include "AlgorithmCommon.h"
    9. //#include "QJsonObject"
    10. //#include "QJsonDocument"
    11. //#include "QJsonArray"
    12. //#include "httplib.h"
    13. //#include "log.h"
    14. //#include "cJSON.h"
    15. HttpServer::HttpServer(std::string ip, int port) : server_ip(ip), server_port(port) {
    16. //event_handler = new AlgorithmAlarmHandler();
    17. }
    18. HttpServer::~HttpServer() {
    19. stopListen();
    20. if (read_thd.joinable()) {
    21. read_thd.join();
    22. }
    23. }
    24. void HttpServer::startListen() {
    25. read_thd = std::thread([=]() {
    26. serverListen();
    27. });
    28. //event_handler->startHandlerThread();
    29. }
    30. void HttpServer::stopListen() {
    31. if (server.is_running()) {
    32. server.stop();
    33. }
    34. }
    35. void HttpServer::serverListen() {
    36. if (!server.is_valid()) {
    37. std::cout << "http server invalid" << std::endl;
    38. return;
    39. }
    40. // 服务器状态
    41. server.Get("/server/status", [&](const Request &req, Response &res) {
    42. onServerStatus(req, res);
    43. });
    44. // 上传算法结果
    45. server.Post("/uploadAlgorithmResult", [&](const Request &req, Response &res) {
    46. onUploadAlgorithmResult(req, res);
    47. });
    48. // 错误处理
    49. server.set_error_handler([&](const Request &req, Response &res) {
    50. onErrorHandle(req, res);
    51. });
    52. //qDebug() << "server start listen";
    53. server.listen(server_ip.c_str(), server_port);
    54. }
    55. void HttpServer::onServerStatus(const httplib::Request &req, httplib::Response &res) {
    56. res.body = R"({"code": 200,"msg": "Server is already Running"})";
    57. }
    58. void HttpServer::onUploadAlgorithmResult(const httplib::Request &req, httplib::Response &res) {
    59. std::string content_type = httputillib::GetContentType(req.headers);
    60. //if (content_type != "application/json") {
    61. // qDebug() << "contentType 异常, content_type:" << QString::fromStdString(content_type);
    62. //}
    63. bool parseRet = parseAlgorithmResult(req.body);
    64. //bool parseRet = true;
    65. std::string rspMsg;
    66. if (parseRet) {
    67. rspMsg = std::string(R"({"msg":"Recv Success, Parse Success."})");
    68. } else {
    69. rspMsg = std::string(R"({"msg":"Recv Success, Parse Failed."})");
    70. }
    71. res.body = std::move(rspMsg);
    72. }
    73. // 错误请求处理
    74. void HttpServer::onErrorHandle(const httplib::Request &req, httplib::Response &res) {
    75. const char *fmt = {"\"error\": \"服务器不支持该方法\""};
    76. char buf[BUFSIZ] = {0};
    77. snprintf(buf, sizeof(buf), fmt, res.status);
    78. res.set_content(buf, "application/json");
    79. }
    80. bool HttpServer::parseAlgorithmResult(const std::string &body) {
    81. //std::cout << "body:" << body << std::endl;
    82. Json::Reader reader;
    83. Json::Value root;
    84. //std::ifstream in(body, std::ios::binary);
    85. //if (!in.is_open()) {
    86. // std::cout << "open file failed" << std::endl;
    87. // return false;
    88. //}
    89. if (!reader.parse(body, root)) {
    90. std::cout << "parse failed" << std::endl;
    91. return false;
    92. }
    93. std::string rtsp = root["rtsp"].asString();
    94. std::cout << "rtsp:" << rtsp << std::endl;
    95. std::string level = root["level"].asString();
    96. std::cout << "level:" << level << std::endl;
    97. std::string type = root["type"].asString();
    98. std::cout << "type:" << type << std::endl;
    99. std::string image = root["image"].asString();
    100. //std::cout << "image:" << image << std::endl;
    101. std::string out = base64_decode(image);
    102. std::string decoded_jpeg = std::move(out);
    103. //std::cout << "decoded_jpeg: " << decoded_jpeg << std::endl;
    104. cv::Mat mat2(1, decoded_jpeg.size(), CV_8U, (char*)decoded_jpeg.data());
    105. cv::Mat dst = cv::imdecode(mat2, CV_LOAD_IMAGE_COLOR);
    106. cv::imwrite(rtsp.substr(1) + ".jpg", dst);
    107. return true;
    108. }

     HttpServer.h如下:

    1. //#ifndef CPPHTTPSERVER_HTTPSERVER_H
    2. //#define CPPHTTPSERVER_HTTPSERVER_H
    3. #include "httputillib.h"
    4. #include "httplib.h"
    5. #include "base64.h"
    6. //#include "thread"
    7. #include
    8. #include
    9. #include
    10. class HttpServer{
    11. public:
    12. HttpServer(std::string ip, int port);
    13. ~HttpServer();
    14. void startListen();
    15. void stopListen();
    16. private:
    17. void serverListen();
    18. // 回调函数: 错误请求处理
    19. void onErrorHandle(const httplib::Request &req, httplib::Response &res);
    20. // 回调函数: 获取服务器状态
    21. void onServerStatus(const httplib::Request &req, httplib::Response &res);
    22. // 回调函数: 上传算法结果
    23. void onUploadAlgorithmResult(const httplib::Request &req, httplib::Response &res);
    24. // 回调函数:处理算法数据
    25. bool parseAlgorithmResult(const std::string &body);
    26. std::string server_ip;
    27. int server_port;
    28. Server server;
    29. std::thread read_thd;
    30. };
    31. //#endif //CPPHTTPLIB_HTTPLIB_H

    httputillib.h如下:

    1. #include
    2. using namespace httplib;
    3. namespace httputillib {
    4. // 打印请求头
    5. static std::string DumpHeaders(const Headers &headers) {
    6. std::string s;
    7. char buf[BUFSIZ] = {0};
    8. for (auto it = headers.begin(); it != headers.end(); ++it) {
    9. const auto &x = *it;
    10. snprintf(buf, sizeof(buf), "%s: %s\n", x.first.c_str(), x.second.c_str());
    11. s += buf;
    12. }
    13. return s;
    14. }
    15. // 从请求同获取content type
    16. static std::string GetContentType(const httplib::Headers &headers) {
    17. auto iter = headers.find("Content-Type");
    18. if (iter == headers.end()) {
    19. return std::string();
    20. }
    21. return iter->second;
    22. }
    23. };

    上述完整代码可详见github或者百度网盘

  • 相关阅读:
    Hadoop如何启动HttpFS服务?
    程序员应该专注技术还是转管理?
    直线导轨在喷涂行业中的应用场景
    Spring学习(4) Spring依赖注入
    SpringBoot官方支持任务调度框架,轻量级用起来也挺香!
    短视频文案提取的简单实现
    C++ 新特性 | C++ 11 | 移动语义与右值引用
    UE4 通过按键切换不同的HUD
    只要做好充分准备,丢失的苹果设备多半可以找回来,包括AirPods
    从0到1开始运营你的开源产品
  • 原文地址:https://blog.csdn.net/zk_ken/article/details/133683687