话不多说,直接上源码
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);