QT使用HTTP上传json格式数据源码分享

话不多说,直接上源码

httpHelper.h

cpp 复制代码
#ifndef HTTPHELPER_H
#define HTTPHELPER_H

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QJsonParseError>
#include <QJsonObject>
#include <QTime>
#include <QEventLoop>
#include <QMutex>
#include <QMap>
#include <QHttpMultiPart>
#include <QUrlQuery>

class HttpHelper : public QObject
{
    Q_OBJECT
public:
    explicit HttpHelper(QObject *parent = nullptr);
    ~HttpHelper();

    void uploadSyncVertifyInfoSlot(QString url,const QMap<QString,QString> body,QString value);
private:
    QNetworkAccessManager *networkAccessManager;
};

#endif // HTTPHELPER_H

httpHelper.cpp

cpp 复制代码
HttpHelper::HttpHelper(QObject *parent)
    : QObject{parent}
{
    this->networkAccessManager = new QNetworkAccessManager(this);
}
HttpHelper::~HttpHelper()
{
    if(this->networkAccessManager)
    {
        this->networkAccessManager->clearAccessCache();
        this->networkAccessManager->destroyed();
        delete this->networkAccessManager;
    }
}
void HttpHelper::uploadSyncVertifyInfoSlot(QString url, const QMap<QString, QString> body, QString value)
{
    this->networkAccessManager->setTransferTimeout(2000);

    //发送异步get请求
    QNetworkRequest request;


    request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
    request.setHeader(QNetworkRequest::ContentLengthHeader, value.toUtf8().size());
    for(QMap<QString,QString>::ConstIterator it = body.begin();it != body.end();it++)
    {
        request.setRawHeader(it.key().toUtf8(),it.value().toUtf8());
    }
    request.setUrl(QUrl(url));
    //qDebug()<<request.url().toString();

    QNetworkReply *reply = this->networkAccessManager->post(request,value.toUtf8());

    connect(reply, &QNetworkReply::finished,
            [=]()
            {
                if(reply->error()!=QNetworkReply::NoError)
                {
                    //处理中的错误信息
                    qWarning()<<"upload reply error:"<<reply->error();
                    qDebug()<<"upload reply error string:"<<reply->errorString();
                    qDebug()<<"upload status code:"<<reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
                    if(reply->isOpen())
                        qDebug()<<"upload response content:"<<reply->readAll();
                }
                else
                {
                    //获取响应信息
                    QByteArray replyData = reply->readAll();
                    qDebug()<<"upload reply:"<<replyData;
                }
                reply->deleteLater();
            });
}

使用方法

cpp 复制代码
//上次数据
QJsonObject jsonObj;
jsonObj["letter_id"] = letterId;
jsonObj["courier_number"] = courierNumber;
jsonObj["attachment"] = attachment;
jsonObj["load_start_time"] = dateTime;
jsonObj["verify_finished_time"] = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
jsonObj["verify_result"] = verifyRes?"Success":"Failed";
jsonObj["batch_no"] = TaskManage::getRunningTask().taskName;

// 将JSON对象包装成一个QJsonDocument
QJsonDocument jsonDoc(jsonObj);

// 将JSON文档转换为字符串
QString jsonString = jsonDoc.toJson(QJsonDocument::Compact);

QString url = R"(https://xxxxxxxxxx)";

QMap<QString,QString> contentMap;
contentMap["Authorization"] = QString("Bearer ").append(token);
this->httpHelper->uploadSyncVertifyInfo(url,contentMap,jsonString);
相关推荐
阿巴~阿巴~17 小时前
自定义协议设计与实践:从协议必要性到JSON流式处理
服务器·网络·网络协议·json·操作系统·自定义协议
颜*鸣&空1 天前
QT实现串口通信+VSPD+串口调试工具
开发语言·qt
Awkwardx1 天前
Linux网络编程—应用层协议HTTP
网络·网络协议·http
颜*鸣&空1 天前
QT程序实现串口通信案例
开发语言·qt
Mu.3871 天前
计算机网络模型
网络·网络协议·计算机网络·安全·http·https
Main. 241 天前
从0到1学习Qt -- 常见控件之显示类控件
qt·学习
我有一棵树1 天前
file 协议与 http 协议的区别:为什么本地 HTML 无法加载相对路径 JS,以及正确的解决方式
javascript·http·html
最笨的羊羊1 天前
Flink CDC系列之:JSON 序列化器JsonRowDataSerializationSchemaUtils
json·flink cdc系列·serialization·json 序列化器·rowdata·schemautils
qq_401700411 天前
Qt中事件循环与并发机制的协同工作
qt
q***49862 天前
SpringCloud系列教程:微服务的未来 (五)枚举处理器、JSON处理器、分页插件实现
spring cloud·微服务·json