C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > Qt HTTP上传json

Qt使用HTTP上传json格式数据

作者:小灰灰搞电子

这篇文章主要为大家详细介绍了Qt如何使用HTTP上传json格式数据,文中的示例代码讲解详细,具有一定的借鉴价值,有需要的小伙伴可以参考一下

话不多说,直接上源码

httpHelper.h

#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

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();
            });
}

具体使用方法

//上次数据
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);

到此这篇关于Qt使用HTTP上传json格式数据的文章就介绍到这了,更多相关Qt HTTP上传json内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文