Qt + HTTP 线程交互类封装

介绍

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

代码

头文件

cpp 复制代码
/**
 * @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

实现文件

cpp 复制代码
#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()
{

}
相关推荐
Mr.Q6 小时前
Qt多边形填充/不填充绘制
qt
可峰科技7 小时前
斗破QT编程入门系列之二:认识Qt:编写一个HelloWorld程序(四星斗师)
开发语言·qt
7年老菜鸡9 小时前
策略模式(C++)三分钟读懂
c++·qt·策略模式
天郁青9 小时前
数据库交互的本地项目:后台管理系统
数据库·交互
梓贤Vigo11 小时前
【Axure高保真原型】2级下钻条形图
交互·产品经理·axure·原型·中继器
huanggang98212 小时前
在Ubuntu22.04上使用Qt Creator开发ROS2项目
qt·ros2
老秦包你会13 小时前
Qt第三课 ----------容器类控件
开发语言·qt
阑梦清川14 小时前
JavaEE初阶---网络原理(五)---HTTP协议
网络·http·java-ee
spygg14 小时前
Qt低版本多网卡组播bug
qt·组播·多网卡组播·qt5.7.0
阿尔帕兹14 小时前
构建 HTTP 服务端与 Docker 镜像:从开发到测试
网络协议·http·docker