c++ - 文件下载 - 文件写入前检查错误

标签 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 输出文件将被写入磁盘。我该如何解决?

最佳答案

你应该使用 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>)));

关于c++ - 文件下载 - 文件写入前检查错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40013178/

相关文章:

qt - 如何删除 Qt WindowFlag?

c++ - 用户提供的 terminate() 函数必须是线程安全的吗?

c++ - map 通过引用

c++ - 计算中的百分比

sql - 如何根据WHERE条件计算值连续出现的次数?

qt - Qt-Window 一小部分的截图

c++ - 为什么我不能专门针对依赖类型使用 nullptr 模板参数?

c++ - 可变模板构造函数和移动构造函数

c++ - 如何使用boost来运行线程另一个带有回调的对象函数

c++ - Google Test 中存储期望值的位置?