码迷,mamicode.com
首页 > 数据库 > 详细

QNetworkAccessManager 的使用

时间:2014-09-24 19:23:47      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   使用   ar   for   

非阻塞式的:

   // 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);
}

 

QNetworkAccessManager 的使用

标签:style   blog   http   color   io   os   使用   ar   for   

原文地址:http://www.cnblogs.com/onetaste/p/QNetworkAccessManager.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!