文件下载 - 在文件写入之前检查错误

时间:2016-10-13 05:45:33

标签: c++ qt c++11 networking

我使用Qt从HTTP下载文件,为此,我使用了两个信号:

connect(currentDownload, SIGNAL(finished()),
        SLOT(downloadFinished()));
connect(currentDownload, SIGNAL(readyRead()),
        SLOT(downloadReadyRead()));

回调:

void DownloadManager::downloadFinished()
{
    output.close();

    if (currentDownload->error()) {
        // download failed
        std::cout << "Failed: [" << currentDownload->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()
                     << "] " << qPrintable(currentDownload->errorString()) << std::endl;
    } else {
        std::cout << "Download succeeded" << std::endl;
    }

    currentDownload->deleteLater();
    startNextDownload();
}

void DownloadManager::downloadReadyRead()
{
    output.write(currentDownload->readAll());
}

我遇到的问题是,如果在下载过程中出于任何原因发生任何错误,我无法弄清楚如何跳过编写输出文件。这不符合逻辑 - 因为我只能在finished()信号发射期间检查错误。在readyRead()信号期间检查错误不会显示任何错误,即使它们存在。在结果中,404输出文件将被写入磁盘。我该如何解决?

1 个答案:

答案 0 :(得分:1)

您应该使用QNetworkRequest来获取所有信息。 请参阅此example

QNetworkAccessManager提供更多信号来解决错误。

QNetworkReply *reply = manager->get(request);
connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
        this, SLOT(slotError(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
        this, SLOT(slotSslErrors(QList<QSslError>)));