• QNetworkAccessManager 的使用


    非阻塞式的:

       // client.h 
       
    class Client : public QObject {
            Q_OBJECT
        public:
            explicit Client(const QString &url);
            void sendData(const QString &data);
        public slots:
            void replyFinished(QNetworkReply* reply);
        private:
            void waitForFinish(const QHttp  &http);
            QNetworkAccessManager* m_manager;
            QString mUrl;
    };
    
    
    // client.cpp
    
    #include <QNetworkAccessManager>
    #include <QNetworkReply>
    #include <QUrl>
    
    Client::Client(const QString &url) {
        mUrl = url;
        m_manager = new QNetworkAccessManager(this);
        connect(m_manager, SIGNAL(finished(QNetworkReply*)), this,
                SLOT(replyFinished(QNetworkReply*)));
    }
    
    void Client::replyFinished(QNetworkReply* reply) { // 应答槽函数
        if (reply && reply->error() == QNetworkReply::NoError) {
            QByteArray data = reply->readAll();
            qDebug() << "---------------------------------
    " <<  data;
        } else {
            // error
        }
        reply->close();
    }
    
    void Client::sendData(const QString &data) { // data为发送的数据
        QNetworkRequest request;
        request.setUrl(QUrl(mUrl)); // 设置url
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); // 设置头信息
        m_manager->post(request, data.toUtf8());
    }

    阻塞式的:

    QString Client::sendData(const QString &data) {
        m_manager = new QNetworkAccessManager(this);
        QNetworkRequest request;
        QEventLoop loop; // 使用QEventLoop实现阻塞
        QNetworkReply *reply;
    
        request.setUrl(QUrl(mUrl));
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
        reply = m_manager->post(request, data.toUtf8());
    
        connect(m_manager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit())); // connect
        loop.exec();
        QByteArray byteArray = reply->readAll();
        qDebug() << byteArray;
        delete reply;
        delete m_manager;
        return QString(byteArray);
    }
  • 相关阅读:
    在sql server中怎样获得正在执行的Sql查询
    在windows中使用VMWare安装Mac OS 10.7
    Scrspy 命令
    Windows Service 小品
    线程同步(一)
    线程基础必知必会(二)
    线程基础必知必会(一)
    准备工作与简介
    Python 正则表达式急速入门
    SQL Server 每日一题--每月销售额
  • 原文地址:https://www.cnblogs.com/onetaste/p/QNetworkAccessManager.html
Copyright © 2020-2023  润新知