我正在使用 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/