循环通过 QNetworkAccessManager get() 例程,在完成时检索顺序

Looping through QNetworkAccessManager get() routines, retrieve order on finish

我有一个 QNetworkAccessManager 作为我的 class 的成员。我将来自该管理器的完成信号连接到我编写的 replyFinished 函数。

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

在一个单独的例程中,我循环访问来自经理的 get 调用

for (int si = 0; si<numLines; si++)
{
    QString line = lines[si];
    manager->get(QNetworkRequest(QUrl(line)));
}

在我的 replyFinished 插槽例程中,我知道我可能不会按照它们在循环中执行的顺序接收信号,但是有什么方法可以获取该信息吗?也就是说,有没有一种巧妙的方法可以在我的 replyFinished 例程中获得 "si" ?感谢您的帮助!

插槽 replyFinished(QNetworkReply*) 接收指向相关回复 object 的指针。此回复 object 包含有关该回复的所有信息(错误代码,headers,下载的数据,内容的 URL),还包含初始请求(QNetworkReply::request())。因此,可以检查请求的 URL 或实际下载内容的 URL。请注意,那些 URL 可能不同。

QNetworkReply::url():

Returns the URL of the content downloaded or uploaded. Note that the URL may be different from that of the original request.

QNetworkReply::request():

Returns the request that was posted for this reply. In special, note that the URL for the request may be different than that of the reply.

void MainWindow::replyFinished(QNetworkReply* reply)
{
    qDebug() << reply->url();
    qDebug() << reply->request().url();
}

QNetworkAccessManager::get() returns 指向 QNetworkReply 对象的指针。该指针与传递给您的 replyFinished() 插槽的指针相同。您可以使用 QMap 来存储 QNetworkReply* 指针和整数的配对(si 在您的代码中)。

这是一个工作示例;

#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QUrl>
#include <QMap>

#include <QtDebug>

QNetworkAccessManager am;
void finished(QNetworkReply* reply);

QMap<QNetworkReply*, int> requests;

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QObject::connect(&am, &QNetworkAccessManager::finished, finished);

    QStringList links;
    links << "http://google.com";
    links << "http://taobao.com";
    links << "http://whosebug.com";
    links << "http://stackexchange.com";
    links << "http://bing.com";


    for (int i=0; i < links.size(); i++)
    {
        requests.insert(am.get(QNetworkRequest(QUrl(links[i]))), i);
    }

    return a.exec();
}

void finished(QNetworkReply* reply)
{
    qDebug() << requests[reply];
}