法一:异步
异步就是使用信号槽的方法实现get/post的异步方法,这样的方式不会产生阻塞,在获取到reply之前可以do other things。
get
void get(const QString &str_url){
const QUrl url = QUrl::fromUserInput(str_url);
QNetworkRequest qnr(url);
QNetworkAccessManager *qnam = new QNetworkAccessManager(this);
connect(qnam, SIGNAL(finished(QNetworkReply *)), this, SLOT(on_http_reply(QNetworkReply *)));
qnam->get(qnr);
}
post
void post(const QString &str_url, const QString &data){
const QUrl url = QUrl::fromUserInput(str_url);
QNetworkRequest qnr(url);
QNetworkAccessManager *qnam = new QNetworkAccessManager(this);
connect(qnam, SIGNAL(finished(QNetworkReply *)), this, SLOT(on_http_reply(QNetworkReply *)));
qnam->put(qnr, data.toUtf8());
}
void on_http_reply(QNetworkReply* reply) {
QByteArray reply_data = reply->readAll();
}
法二:同步/阻塞
有时候需要等待得到返回信息才能继续做下一步。这时候用异步就超级难用了,就需要用同步/阻塞的方式了。
get
QByteArray get(const QString &str_url){
const QUrl url = QUrl::fromUserInput(str_url);
QNetworkRequest qnr(url);
QNetworkAccessManager qnam;
QNetworkReply *reply = qnam.get(qnr);
QEventLoop eventloop;
QObject::connect(reply, &QNetworkReply::finished, &eventloop, &QEventLoop::quit);
eventloop.exec(QEventLoop::ExcludeUserInputEvents);
QByteArray reply_data = reply->readAll();
reply->deleteLater();
reply = nullptr;
return reply_data;
}
post
QByteArray post(const QString &str_url, const QString &data){
const QUrl url = QUrl::fromUserInput(str_url);
QNetworkRequest qnr(url);
QNetworkAccessManager qnam;
QNetworkReply *reply = qnam.put(qnr, data.toUtf8());
QEventLoop eventloop;
QObject::connect(reply, &QNetworkReply::finished, &eventloop, &QEventLoop::quit);
eventloop.exec(QEventLoop::ExcludeUserInputEvents);
QByteArray reply_data = reply->readAll();
reply->deleteLater();
reply = nullptr;
return reply_data;
}