首页 > 代码库 > QNetworkAccessManager 的使用
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);}
QNetworkAccessManager 的使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。