如何同步QNetworkAccessManager?

时间:2013-08-29 12:54:53

标签: c++ qt asynchronous synchronization

我的deleteIdList变量来自replyFinished(QNetworkReply*)函数。但是deleteIdList变量返回空。但是,它必须返回任何内容..我想同步QNetworkAccessManager ..

    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));

    foreach (QString delIdList, deleteIdList) {

    serviceUrl = "http://localhost:8080/limit_id="+delIdList+"&false";
    requestUrl = QString("%1%2:%3%4").arg(scheme).arg(qstr).arg(QString::number(svcPort)).arg(serviceUrl);

    QUrl url(requestUrl);
    QNetworkRequest request;
    request.setUrl(url);
    manager->get(request);

  }

如何同步QNetworkAccessManager?

3 个答案:

答案 0 :(得分:1)

我可能会迟到,但我认为它可以帮助其他人面对这个问题。

QNetworkAccessManager *networkMgr = new QNetworkAccessManager(this);
QNetworkReply *reply = networkMgr->get( QNetworkRequest( QUrl( "http://www.google.com" ) ) );

QEventLoop loop;
QObject::connect(reply, SIGNAL(readyRead()), &loop, SLOT(quit()));

// Execute the event loop here, now we will wait here until readyRead() signal is emitted
// which in turn will trigger event loop quit.
loop.exec();

// Lets print the HTTP GET response.
qDebug( reply->readAll());

Source : developer.nokia.com

答案 1 :(得分:0)

呃...你在做什么?您创建了一个QNetWorkManager,将完成的信号连接到replyFinished插槽并期望得到一个结果,该结果来自您甚至在发送请求之前的replyFinished?对不起,但是从我在您的代码中看到的内容来看,我说它无法修复。

如果deleteIdList以某种方式是您的请求的结果,则foreach (QString delIdList, deleteIdList)必须位于replyFinished插槽中。并且

    QUrl url(requestUrl);
    QNetworkRequest request;
    request.setUrl(url);
    manager->get(request);

必须位于连接下方的循环之外。但是,当然,你的代码是错误的,我的提示'关于可能打算做什么的粗略猜测工作。

答案 2 :(得分:0)

理解这个问题有点困难 - 但我有一些建议,不过是:永远不要使用QNetworkAccessManager的完成信号。而是连接到QNetworkReply的完成插槽。

QNetworkAccessManager *manager = new QNetworkAccessManager(this);

foreach (QString delIdList, deleteIdList) {

    serviceUrl = "http://localhost:8080/limit_id="+delIdList+"&false";
    requestUrl = QString("%1%2:%3%4").arg(scheme).arg(qstr).arg(QString::number(svcPort)).arg(serviceUrl);

    QUrl url(requestUrl);
    QNetworkRequest request;
    request.setUrl(url);
    QNetworkReply *reply = manager->get(request);
    connect(reply,SIGNAL(finished()),this,SLOT(replyFinished()));
}

然后在replyFinished插槽中,您可以调用sender()来接收指向回复的指针。通过这种方式,您可以“同步”并确定哪个回复属于哪个请求。