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() << "---------------------------------\n" <<  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);
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。