http发送和接收图片json文件

这篇具有很好参考价值的文章主要介绍了http发送和接收图片json文件。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

 一、http数据发送

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

std::string detectNet::Mat2Base64(const cv::Mat &image, std::string imgType){
    std::vector<uchar> buf;
    cv::imencode(imgType, image, buf);
    //uchar *enc_msg = reinterpret_cast<unsigned char*>(buf.data());
    std::string img_data = base64_encode(buf.data(), buf.size(), false);
    return img_data;
}

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

void detectNet::send_json_people(cv::Mat img, std::string label, std::string level, std::string rtsp){
    std::string out = Mat2Base64(img,".jpg");
    //std::cout << out << std::endl;

    ImgInfo imgInfo(out, label, level, rtsp);
    static auto client = httplib::Client("127.0.0.1", 18080);
    auto result = client.Post("/uploadAlgorithmResult", imgInfo.to_json_people(), "application/json");
    if (result != nullptr && result->status == 200) {
        std::cout << result->body << std::endl;
    }
}

其中 ImgInfo 类为:

#ifndef HTTP_DEMO_IMGINFO_H
#define HTTP_DEMO_IMGINFO_H

#include <utility>

#include "cJSON.h"
#include "base64.h"


#define RTSP_URL "rtsp://admin:a123456789@192.168.8.31:554/h264/ch1/main/av_stream/1"
#define AlgorithmType "hook_detection"
#define AlgorithmType_people "danger_zone"
#define AlgorithmType_crooked "crooked"

class ImgInfo {
private:
    std::string img;
    std::string label;
    std::string rtsp;
    std::string level;
public:
    ImgInfo(std::string img, std::string label, 
            std::string level, std::string rtsp) : img(std::move(img)), label(std::move(label)),
                                 level(std::move(level)), rtsp(std::move(rtsp)) {}

    std::string to_json_people() {
        auto *root = cJSON_CreateObject();
        cJSON_AddStringToObject(root, "image", img.c_str());
        cJSON_AddStringToObject(root, "level", level.c_str());
        cJSON_AddStringToObject(root, "rtsp", rtsp.c_str());
        cJSON_AddStringToObject(root, "type", AlgorithmType_people);
        cJSON_AddStringToObject(root, "label", label.c_str());


        /*
        cJSON *label_array = cJSON_CreateArray();
        for (auto &i: label) {
            cJSON_AddItemToArray(label_array, cJSON_CreateString(i.c_str()));
        }
        cJSON_AddItemToObject(root, "label", label_array);
        */
        char *out = cJSON_Print(root);
        std::string res = out;
        free(out);
        cJSON_Delete(root);
        return res;
    }
};

#endif //HTTP_DEMO_IMGINFO_H

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

二、http数据接收

HttpServer.cpp如下: 

//#include <QFile>
//#include <FileUtils.hpp>
#include "HttpServer.h"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
//#include "QString"
//#include "TimeUtils.hpp"
//#include "AlgorithmCommon.h"
//#include "QJsonObject"
//#include "QJsonDocument"
//#include "QJsonArray"
//#include "httplib.h"

//#include "log.h"
//#include "cJSON.h"

HttpServer::HttpServer(std::string ip, int port) : server_ip(ip), server_port(port) {

    //event_handler = new AlgorithmAlarmHandler();

}

HttpServer::~HttpServer() {
    stopListen();
    if (read_thd.joinable()) {
        read_thd.join();
    }
}

void HttpServer::startListen() {
    read_thd = std::thread([=]() {
        serverListen();
    });
    //event_handler->startHandlerThread();
}

void HttpServer::stopListen() {
    if (server.is_running()) {
        server.stop();
    }
}

void HttpServer::serverListen() {
    if (!server.is_valid()) {
        std::cout << "http server invalid" << std::endl;
        return;
    }

    // 服务器状态
    server.Get("/server/status", [&](const Request &req, Response &res) {
        onServerStatus(req, res);
    });

    // 上传算法结果
    server.Post("/uploadAlgorithmResult", [&](const Request &req, Response &res) {
        onUploadAlgorithmResult(req, res);
    });


    // 错误处理
    server.set_error_handler([&](const Request &req, Response &res) {
        onErrorHandle(req, res);
    });

    //qDebug() << "server start listen";
    server.listen(server_ip.c_str(), server_port);
}

void HttpServer::onServerStatus(const httplib::Request &req, httplib::Response &res) {
    res.body = R"({"code": 200,"msg": "Server is already Running"})";
}

void HttpServer::onUploadAlgorithmResult(const httplib::Request &req, httplib::Response &res) {
    std::string content_type = httputillib::GetContentType(req.headers);
    //if (content_type != "application/json") {
   //     qDebug() << "contentType 异常, content_type:" << QString::fromStdString(content_type);
    //}
    bool parseRet = parseAlgorithmResult(req.body);
	//bool parseRet = true;
    std::string rspMsg;
    if (parseRet) {
        rspMsg = std::string(R"({"msg":"Recv Success, Parse Success."})");
    } else {
        rspMsg = std::string(R"({"msg":"Recv Success, Parse Failed."})");
    }
    res.body = std::move(rspMsg);
}


// 错误请求处理
void HttpServer::onErrorHandle(const httplib::Request &req, httplib::Response &res) {
    const char *fmt = {"\"error\": \"服务器不支持该方法\""};
    char buf[BUFSIZ] = {0};
    snprintf(buf, sizeof(buf), fmt, res.status);

    res.set_content(buf, "application/json");
}


bool HttpServer::parseAlgorithmResult(const std::string &body) {

    //std::cout << "body:" << body << std::endl;
	Json::Reader reader;
	Json::Value root;
    //std::ifstream in(body, std::ios::binary);
    //if (!in.is_open()) {
    //    std::cout << "open file failed" << std::endl;
    //    return false;
    //}
    if (!reader.parse(body, root)) {
        std::cout << "parse failed" << std::endl;
        return false;
    }
    std::string rtsp = root["rtsp"].asString();
    std::cout << "rtsp:" << rtsp << std::endl;
    std::string level = root["level"].asString();
    std::cout << "level:" << level << std::endl;
    std::string type = root["type"].asString();
    std::cout << "type:" << type << std::endl;
	std::string image = root["image"].asString();
    //std::cout << "image:" << image << std::endl;
	std::string out = base64_decode(image);
    std::string decoded_jpeg = std::move(out);
    //std::cout << "decoded_jpeg: " << decoded_jpeg << std::endl;

	cv::Mat mat2(1, decoded_jpeg.size(), CV_8U, (char*)decoded_jpeg.data());
    cv::Mat dst = cv::imdecode(mat2, CV_LOAD_IMAGE_COLOR);
	cv::imwrite(rtsp.substr(1) + ".jpg", dst);  

    return true;
}

 HttpServer.h如下:

//#ifndef CPPHTTPSERVER_HTTPSERVER_H
//#define CPPHTTPSERVER_HTTPSERVER_H

#include "httputillib.h"
#include "httplib.h"
#include "base64.h"
//#include "thread"
#include <thread>
#include <time.h>

#include <json.h>


class HttpServer{
public:
    HttpServer(std::string ip, int port);
    ~HttpServer();

    void startListen();

    void stopListen();

private:

    void serverListen();

    // 回调函数: 错误请求处理
    void onErrorHandle(const httplib::Request &req, httplib::Response &res);

    // 回调函数: 获取服务器状态
    void onServerStatus(const httplib::Request &req, httplib::Response &res);

    // 回调函数: 上传算法结果
    void onUploadAlgorithmResult(const httplib::Request &req, httplib::Response &res);

    // 回调函数:处理算法数据
    bool parseAlgorithmResult(const std::string &body);

    std::string server_ip;
    int server_port;

    Server server;
    std::thread read_thd;

};

//#endif //CPPHTTPLIB_HTTPLIB_H

httputillib.h如下:

#include <httplib.h>

using namespace httplib;


namespace httputillib {
// 打印请求头
static std::string DumpHeaders(const Headers &headers) {
	std::string s;
	char buf[BUFSIZ] = {0};

	for (auto it = headers.begin(); it != headers.end(); ++it) {
		const auto &x = *it;
		snprintf(buf, sizeof(buf), "%s: %s\n", x.first.c_str(), x.second.c_str());
		s += buf;
	}

	return s;
}

// 从请求同获取content type
static std::string GetContentType(const httplib::Headers &headers) {
	auto iter = headers.find("Content-Type");
	if (iter == headers.end()) {
		return std::string();
	}

	return iter->second;
}

};

上述完整代码可详见github或者百度网盘文章来源地址https://www.toymoban.com/news/detail-727064.html

到了这里,关于http发送和接收图片json文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • C/C++ 发送与接收HTTP/S请求

    HTTP(Hypertext Transfer Protocol)是一种用于传输超文本的协议。它是一种无状态的、应用层的协议,用于在计算机之间传输超文本文档,通常在 Web 浏览器和 Web 服务器之间进行数据通信。HTTP 是由互联网工程任务组(IETF)定义的,它是基于客户端-服务器模型的协议,其中客户端

    2024年02月05日
    浏览(42)
  • vue使用axios发送post请求携带json body参数,后端使用@RequestBody进行接收

    最近在做自己项目中,做一个非常简单的新增用户场景,但是使用原生axios发送post请求的时候,还是踩了不少坑的。 唉,说多了都是泪,小小一个新增业务,在自己前后端一起开发的时候,硬是搞了好久。 下面就把问题总结分享下,防止后人再踩坑。 首先先看下我的接口定

    2024年02月02日
    浏览(40)
  • .net6 接收json数据 Controller http post

    .net6 接收json数据 Controller http post 要添加这两个包 前端ajax请求 关键在contentType 和JSON.stringify 如果这2两个没加上后台还是接收不到的! contentType: “application/json”, 后台接收加上一个 [FromBody] 后台示例 后台完整代码

    2024年02月05日
    浏览(25)
  • MFC发送http https以及json解析

    请求三部曲:

    2024年02月05日
    浏览(29)
  • Qt 使用HTTP请求网络API并接收返回的JSON格式的数据

    引入网络模块: mainwindow.h: mainwindow.cpp:

    2024年02月13日
    浏览(37)
  • java http get post 和 发送json数据请求

    浏览器请求效果       main调用  

    2024年02月16日
    浏览(38)
  • postman如何发送json请求其中file字段是一个图片

    在Postman中发送一个包含文件(如图片)的JSON请求通常意味着你需要发送一个multipart/form-data请求。因为在JSON中直接嵌入二进制文件数据(如图片)通常不是一个有效的做法。下面是如何在Postman中发送这样的请求的步骤: 打开Postman并创建一个新的请求 。 设置请求类型为 PO

    2024年04月28日
    浏览(22)
  • FormData异步发送文件,后端SpringBoot接收

    平时我们用表单提交数据时,所有的数据都是以键值对的形式提交给后端的,对于文件二进制流数据也是以键值对提交的,只是说此时值的内容是二进制数据罢了。如果我们想给后端上传文件,一般都是利用表单里的File控件去提交的,但这时候有一个问题,这种上传方式不是

    2024年02月15日
    浏览(31)
  • Go语言项目后端使用gin框架接收前端发送的三种格式数据(form-data,json,Params)

    使用gin框架的BindJSON方法,将前端的json格式数据将后端的结构体相绑定,从而获取到前端所发送的数据,并返回给前端 1.将前端发送过来的数据全部返回 2.将前端发送过来的json格式数据选择性返回   使用gin框架的PostForm方法,从而获取到前端form格式的参数 使用gin框架中的

    2024年02月01日
    浏览(36)
  • C# 使用Http Post方式发送Json数据,只需二步。

    一.先在工程增加 RestClient.cs类 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Web; namespace CM2.CentreWin { class RestClient { private System.Net.CookieContainer Cookies = new System.Net.CookieContainer(); priv

    2024年02月09日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包