QNetworkAccessManager的学习

发布时间:2024年01月22日

Qt 之 全局的QNetworkAccessManager_全局的 qnetworkaccessmanager 对象-CSDN博客

qt中,建议一个程序使用一个QNetworkAccessManager即可。

示例程序:

#ifndef NET_H
#define NET_H

#include <QObject>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork>
class net : public QObject
{
    Q_OBJECT
public:
    explicit net(QObject *parent = nullptr);
    void sendRequest();
signals:

public slots:

private:
    QNetworkAccessManager * manager;
};

#endif // NET_H
#include "net.h"
#include <QJsonDocument>
#include <QJsonParseError>
#include <QFile>
#include <QCoreApplication>
#include <QEventLoop>
net::net(QObject *parent) : QObject(parent)
{
    manager = new QNetworkAccessManager(this);
}

void net::sendRequest()
{
    QString url="xxx";

    QFile file(QCoreApplication::applicationDirPath()+"/1.json");
    file.open(QIODevice::ReadOnly);
    QJsonParseError error;
    QJsonDocument qJsonDocument=QJsonDocument::fromJson(file.readAll(),&error);
    //qDebug()<<QCoreApplication::applicationDirPath()+"/1.json";
    if(error.error!=QJsonParseError::NoError)
    {
        qDebug()<<"parseJson:"<<error.errorString();
        return ;
    }

    QNetworkRequest requestInfo;
    requestInfo.setUrl(QUrl(url));
    requestInfo.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
    QNetworkReply *reply = manager->post(requestInfo, qJsonDocument.toJson());

    QEventLoop temp_loop;
    QObject::connect(reply, &QNetworkReply::finished, &temp_loop, &QEventLoop::quit);
    temp_loop.exec();
    if(reply->error()==QNetworkReply::NoError)
    {
         QByteArray bytes = reply->readAll();
         //qDebug()<<bytes;
         static int count=0;
         qDebug()<<"count:"<<count;
         count++;
   }
   else {
         qDebug() << reply->error();
   }
   reply->deleteLater();
}

当reply发出finished()信号时,temp_loop退出事件循环。?

#include <QCoreApplication>
#include "net.h"
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    net n;
    for(int i=0;i<10;i++)
    {
        n.sendRequest();
    }
    return a.exec();
}

输出:

count: 0
count: 1
count: 2
count: 3
count: 4
count: 5
count: 6
count: 7
count: 8
count: 9

当本机断网后:

QNetworkReply::NetworkError(HostNotFoundError)
QNetworkReply::NetworkError(HostNotFoundError)
QNetworkReply::NetworkError(HostNotFoundError)
QNetworkReply::NetworkError(HostNotFoundError)
QNetworkReply::NetworkError(HostNotFoundError)
QNetworkReply::NetworkError(HostNotFoundError)
QNetworkReply::NetworkError(HostNotFoundError)
QNetworkReply::NetworkError(HostNotFoundError)
QNetworkReply::NetworkError(HostNotFoundError)
QNetworkReply::NetworkError(HostNotFoundError)

第二种写法:

#ifndef NET_H
#define NET_H

#include <QObject>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork>
class net : public QObject
{
    Q_OBJECT
public:
    explicit net(QObject *parent = nullptr);
    void sendRequest();
signals:

public slots:
    void finishedSlot();
private:
    QNetworkAccessManager * manager;
};

#endif // NET_H
#include "net.h"
#include <QJsonDocument>
#include <QJsonParseError>
#include <QFile>
#include <QCoreApplication>
#include <QEventLoop>
net::net(QObject *parent) : QObject(parent)
{
    manager = new QNetworkAccessManager(this);
}

void net::sendRequest()
{
    QString url="http://www.zsapi.soft.y01.cn/module/device/api/index/?action=op";

    QFile file(QCoreApplication::applicationDirPath()+"/1.json");
    file.open(QIODevice::ReadOnly);
    QJsonParseError error;
    QJsonDocument qJsonDocument=QJsonDocument::fromJson(file.readAll(),&error);
    //qDebug()<<QCoreApplication::applicationDirPath()+"/1.json";
    if(error.error!=QJsonParseError::NoError)
    {
        qDebug()<<"parseJson:"<<error.errorString();
        return ;
    }

    QNetworkRequest requestInfo;
    requestInfo.setUrl(QUrl(url));
    requestInfo.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
    QNetworkReply *reply = manager->post(requestInfo, qJsonDocument.toJson());
    QObject::connect(reply, &QNetworkReply::finished, this, &net::finishedSlot);
}

void net::finishedSlot()
{
    QNetworkReply *reply=(QNetworkReply *)sender();
    if(reply->error()==QNetworkReply::NoError)
    {
         QByteArray bytes = reply->readAll();
         //qDebug()<<bytes;
         static int count=0;
         qDebug()<<"count:"<<count;
         count++;
   }
   else {
         qDebug() << reply->error();
   }
    reply->deleteLater();
}
#include <QCoreApplication>
#include "net.h"
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    net n;
    for(int i=0;i<10;i++)
    {
        n.sendRequest();
    }
    return a.exec();
}

第三种写法:

#ifndef NET_H
#define NET_H

#include <QObject>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork>
class net : public QObject
{
    Q_OBJECT
public:
    explicit net(QObject *parent = nullptr);
    void sendRequest();
signals:

public slots:
    void finishedSlot(QNetworkReply *reply);
private:
    QNetworkAccessManager * manager;
};

#endif // NET_H
#include "net.h"
#include <QJsonDocument>
#include <QJsonParseError>
#include <QFile>
#include <QCoreApplication>
#include <QEventLoop>
net::net(QObject *parent) : QObject(parent)
{
    manager = new QNetworkAccessManager(this);
    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(finishedSlot(QNetworkReply*)),Qt::DirectConnection);
}

void net::sendRequest()
{
    QString url="http://www.zsapi.soft.y01.cn/module/device/api/index/?action=op";

    QFile file(QCoreApplication::applicationDirPath()+"/1.json");
    file.open(QIODevice::ReadOnly);
    QJsonParseError error;
    QJsonDocument qJsonDocument=QJsonDocument::fromJson(file.readAll(),&error);
    //qDebug()<<QCoreApplication::applicationDirPath()+"/1.json";
    if(error.error!=QJsonParseError::NoError)
    {
        qDebug()<<"parseJson:"<<error.errorString();
        return ;
    }

    QNetworkRequest requestInfo;
    requestInfo.setUrl(QUrl(url));
    requestInfo.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
    manager->post(requestInfo, qJsonDocument.toJson());
}

void net::finishedSlot(QNetworkReply *reply)
{
    if(reply->error()==QNetworkReply::NoError)
    {
         QByteArray bytes = reply->readAll();
         //qDebug()<<bytes;
         static int count=0;
         qDebug()<<"count:"<<count;
         count++;
   }
   else {
         qDebug() << reply->error();
   }
    reply->deleteLater();
}

?思考:如何合理使用一个QNetworkAccessManager,来管理所有网络请求呢?

第四种写法:

更灵活一点:

传入url,传出QJsonDocument,再进行处理。

net类只负责发送请求,返回相关数据。

#ifndef NET_H
#define NET_H

#include <QObject>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork>
class net : public QObject
{
    Q_OBJECT
public:
    explicit net(QObject *parent = nullptr);
    QJsonDocument sendRequest(QString url);
signals:

private:
    QNetworkAccessManager * manager;
};

#endif // NET_H
#include "net.h"
#include <QJsonDocument>
#include <QJsonParseError>
#include <QFile>
#include <QCoreApplication>
#include <QEventLoop>
net::net(QObject *parent) : QObject(parent)
{
    manager = new QNetworkAccessManager(this);
}

QJsonDocument net::sendRequest(QString url)
{
    QNetworkRequest requestInfo;
    requestInfo.setUrl(QUrl(url));
    requestInfo.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
    QNetworkReply *reply = manager->get(requestInfo);
    QEventLoop temp_loop;
    QObject::connect(reply, &QNetworkReply::finished, &temp_loop, &QEventLoop::quit);
    temp_loop.exec();
    QJsonDocument doc;
    if(reply->error()==QNetworkReply::NoError)
    {
        QByteArray bytes = reply->readAll();
        doc=QJsonDocument::fromJson(bytes);
        static int count=0;
        qDebug()<<"count:"<<count;
        count++;
        return doc;
   }
   else {
         qDebug() << reply->error();
   }
   reply->deleteLater();
   return doc;
}
#include <QCoreApplication>
#include "net.h"
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString url="http://t.weather.itboy.net/api/weather/city/101010100";

    net n;
    for(int i=0;i<10;i++)
    {
        qDebug()<<n.sendRequest(url);
    }
    return a.exec();
}

文章来源:https://blog.csdn.net/weixin_51883798/article/details/135748059
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。