Qt + HTTP 线程交互类封装

文章介绍了如何在Qt中使用HTTP模块创建一个封装的交互类HttpController,包括线程安全的请求发送、JSON数据处理以及时间日期设置功能。
摘要由CSDN通过智能技术生成

介绍

QT的HTTP模块封装的交互类,线程运行。使用时添加自己的业务逻辑即可

代码

头文件

/**
 * @file httpcontroller.h
 * @brief 云台相机的协议交互类
 * @author xintong-zhou
 * @date 2024-03-13
 */

#ifndef HTTPCONTROLLER_H
#define HTTPCONTROLLER_H

#include <QNetworkReply>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QUrlQuery>
#include <QHttpMultiPart>
#include <QHttpPart>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonValue>
#include <QCryptographicHash>
#include <QThread>

class HttpWorker : public QObject
{
    Q_OBJECT

public:
    HttpWorker();
    ~HttpWorker();

    /**
     * @brief 某条信息的处理
     * @param object json对象
     */
    void dealXXInfo(const QJsonObject &object);


public slots:
    /**
     * @brief 执行请求
     * @param url 请求地址
     * @param arg 请求参数
     */
    void slotPostHttpRequest(const QString &url, const QJsonObject &obj);

    /**
     * @brief 保存交互返回数据
     */
    void slotReadyRead();
    void slotReplyFinished();

    /**
     * @brief 返回数据接收完毕分发处理
     * @param recvBuffer 接收到的json数据
     */
    void slotRecvData(const QByteArray &recvBuffer);


signals:
    /**
     * @brief 向上转发结果
     */
    void sigResult();

private:
    QNetworkAccessManager *m_pManager = nullptr;
};


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

    /**
     * @brief 设置时间日期
     * @param datetime 时间日期
     */
    void setDateTimeInfo(const QDateTime &datetime);

public slots:
    /**
     * @brief 线程退出
     */
    void slotExitThread();

    /**
     * @brief 向上转发结果
     */
    void slotResult();

signals:
    /**
     * @brief 执行请求
     * @param url 请求地址
     * @param arg 请求参数
     */
    void sigPostHttpRequest(const QString &url, const QJsonObject &obj);

private:
    //工作类、线程
    HttpWorker *m_pWorker = nullptr;
    QThread m_thread;

    //请求url以及参数值
    QString m_serverIP;
    QString m_url;
    QString m_arg;
};

#endif // HTTPCONTROLLER_H

实现文件

#include "httpcontroller.h"


HttpWorker::HttpWorker()
{
    m_pManager = new QNetworkAccessManager(this);
}

HttpWorker::~HttpWorker()
{
    if(m_pManager != nullptr)
    {
        delete m_pManager;
        m_pManager = nullptr;
    }
}

void HttpWorker::dealXXInfo(const QJsonObject &object)
{

}

void HttpWorker::slotPostHttpRequest(const QString &url, const QJsonObject &obj)
{
    QJsonDocument jsonDoc = QJsonDocument(obj);
    QByteArray argInfo = jsonDoc.toJson(QJsonDocument::Compact);
    qDebug() << "post HttpRequest" << url << argInfo;

    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader, argInfo.length());

    QNetworkReply *reply = m_pManager->post(request, argInfo);
    connect(reply, &QNetworkReply::readyRead, this, &HttpWorker::slotReadyRead);
    connect(reply, &QNetworkReply::finished, this, &HttpWorker::slotReplyFinished);

}

void HttpWorker::slotReadyRead()
{

}

void HttpWorker::slotReplyFinished()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if(reply == nullptr)
    {
        qDebug() << "replyFinished Reply nullptr";
        return;
    }

    QByteArray byteArray = reply->readAll();
    if(byteArray.isEmpty())
    {
        qDebug() << "replyFinished ByteArray empty";
        return;
    }

    //处理最终数据
    slotRecvData(byteArray);

    //清理资源
    reply->deleteLater();
}

void HttpWorker::slotRecvData(const QByteArray &recvBuffer)
{
    QJsonParseError jsonerror;
    QJsonDocument doc = QJsonDocument::fromJson(recvBuffer, &jsonerror);
    if (doc.isNull() || jsonerror.error != QJsonParseError::NoError)
    {
        QString info(recvBuffer);
        if(!info.isEmpty())
        {
            qDebug() << "recvData parseJson error" << jsonerror.errorString() << info;
        }

        return;
    }

    //解析json数据
    QJsonObject object = doc.object();
    QString cmd = object.value("cmd").toString();
    QJsonObject paramObj = object.value("param").toObject();

    //进行业务分发
    if("timeSetWeb" == cmd)
    {
        dealXXInfo(object);
    }
    else if("timeSetWeb" == cmd)
    {

    }
}


HttpController::HttpController(QObject *parent) : QObject(parent)
{
    //请求url
    m_serverIP = "192.168.25.111";
    m_url = m_serverIP + "/api/XX";

    m_pWorker = new HttpWorker();
    m_pWorker->moveToThread(&m_thread);

    connect(&m_thread, &QThread::finished, this,&HttpController::slotExitThread);
    connect(this, &HttpController::sigPostHttpRequest, m_pWorker, &HttpWorker::slotPostHttpRequest);
    connect(m_pWorker, &HttpWorker::sigResult, this, &HttpController::slotResult);

    m_thread.start();
}

HttpController::~HttpController()
{
    if(m_pWorker)
    {
        delete m_pWorker;
        m_pWorker = nullptr;
    }

    slotExitThread();
}

void HttpController::setDateTimeInfo(const QDateTime &datetime)
{
    //封装信息
    QJsonObject obj;
    obj.insert("cmd", "timeSetWeb");
    QJsonObject param;
    param.insert("token", 0);
    param.insert("dateformat", 0);
    param.insert("timeformat", 1);
    param.insert("manually", 0);
    param.insert("year", datetime.date().year());
    param.insert("month", datetime.date().month());
    param.insert("day", datetime.date().day());
    param.insert("hour", datetime.time().hour());
    param.insert("minute", datetime.time().minute());
    param.insert("second", datetime.time().second());
    obj.insert("param", param);

    emit sigPostHttpRequest(m_url, obj);
}

void HttpController::slotExitThread()
{
    m_thread.quit();
    m_thread.wait();
}

void HttpController::slotResult()
{

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你是周小哥啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值