非阻塞式的:
// 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); }