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);
相关推荐
coder_Alaric2 小时前
[笔记]Qt下使用SendMessage、PostMessage和接收window消息
笔记·qt
鲁班相信爱情2 小时前
QT中静态变量无法翻译的问题
开发语言·qt
ymchuangke3 小时前
Pyside6 --Qt设计师--简单了解各个控件的作用之:Item Views
python·qt·ui·pyside6
m0_748230443 小时前
HTTP、WebSocket、gRPC 或 WebRTC:各种协议的区别
websocket·http·webrtc
淼淼7633 小时前
qt中tr的使用
开发语言·qt
领头羊leo4 小时前
【计算机网络】HTTP,DHCP, NTP&NAT
网络协议·计算机网络·http
雅典没有娜4 小时前
QT/C++与LUA交互过程中,利用ZeroBraneStudio对LUA脚本进行仿真调试
c++·qt·lua·调试·仿真·zerobranestudio
weixin_399264295 小时前
QT c++ 测控系统 一套报警规则(上)
c++·qt
火山上的企鹅5 小时前
Qt WORD/PDF(二)使用 QtPdfium库实现 PDF操作、打印等
qt·qwidget·qtpdfium