在Qt与Http通信的时候,会根据不同的情况使用同步或者异步的方式进行数据请求。
同步,即发送Http请求之后,会一直等待服务器返回的数据,接收到数据之前,程序一直阻塞。
异步,即发送Http请求之后,程序可以继续往下执行,接收到服务器返回的数据时自动调用其对应的槽函数处理数据。
同步需要在发送请求之后,放置一个QEnentLoop,而异步只需要绑定对应的槽函数即可。
同步Demo:
QUrl url(myurl);QNetworkReply *reply = quitmanager->get(QNetworkRequest(QUrl(url)));QEventLoop eventLoop;connect(quitmanager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));eventLoop.exec(); //block until finish//reply->readall()reply->deleteLater();reply = nullptr;return true;
异步Demo:
QNetworkAccessManager *manager = new QNetworkAccessManager;QNetworkRequest *request = new QNetworkRequest;connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(finishedSlot(QNetworkReply*)));//绑定槽函数//get post请求二选一QUrl url(urlHead+"exam_start/"+studentId);request->setUrl(url);manager->get(*request);//发送get请求QByteArray postData = document.toJson(QJsonDocument::Compact);request->setUrl(url);request->setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));manager->post(*request, postData);//发送post请求
槽函数
void MainWindow::finishedSlot(QNetworkReply *reply)
{qDebug() << "进入函数: " << __FUNCTION__;QString json = reply->readAll();//这个返回的JSON包所携带的所有信息QJsonParseError jsonerror;QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8(), &jsonerror);if (!doc.isNull() && jsonerror.error == QJsonParseError::NoError){QJsonObject object = doc.object();if(object.contains("type")){switch (object.value("type").toInt()){case 1:parseLogJason(object);break;case 2:parseParameterJason(object);break;case 3:parseExamStartJason(object);break;case 4:parseExamEndJason(object);break;default:return;}}}
}
异步也可以将槽函数写在函数内 依然是异步
QNetworkAccessManager* manager6 = new QNetworkAccessManager(this);// 准备工作 - 初始化一个QNetworkRequestQNetworkRequest res6;//设置头 - 浏览器res6.setHeader(QNetworkRequest::UserAgentHeader,"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36");res6.setUrl(QUrl("http://" + IP + "/version"));QNetworkReply* reply6 = manager6->get(res6);reply6->attribute(QNetworkRequest::HttpStatusCodeAttribute);reply6->attribute(QNetworkRequest::RedirectionTargetAttribute);// 读服务器回写的数据connect(reply6, &QNetworkReply::readyRead, this, [=](){//QVariant str = reply6->header(QNetworkRequest::LocationHeader);QByteArray data = reply6->readAll();//qDebug() << "version "<< data ;QString str = QString(data);int pos = str.indexOf('-');version[node_id] = str.mid(pos + 3, 2) + "."+ str.mid(0, pos ) ;reply6->abort();reply6->close();reply6->deleteLater();manager6->deleteLater();});