QT学习笔记-29.使用QT HTTP下载网络文件
QT附带的例子比较好:
1.开始下载
2.取消下载
3.预备下载
4.下载完成
5.进度回调
等
实现为:
获取url链接,生成本地文件,...
要点:
1.针对QNetReply绑定需要的信号和槽
2.实现需要的槽函数
class HttpWindow : public QDialog
{
Q_OBJECT
public:
HttpWindow(QWidget *parent = 0);
void startRequest(QUrl url);
private slots:
void downloadFile();
void cancelDownload();
void httpFinished();
void httpReadyRead();
void updateDataReadProgress(qint64 bytesRead, qint64 totalBytes);
void enableDownloadButton();
void slotAuthenticationRequired(QNetworkReply*,QAuthenticator *);
private:
QLabel *statusLabel;
QLabel *urlLabel;
QLineEdit *urlLineEdit;
QProgressDialog *progressDialog;
QPushButton *downloadButton;
QPushButton *quitButton;
QDialogButtonBox *buttonBox;
QUrl url;
QNetworkAccessManager qnam;
QNetworkReply *reply;
QFile *file;
int httpGetId;
bool httpRequestAborted;
};
其中槽有:{
Q_OBJECT
public:
HttpWindow(QWidget *parent = 0);
void startRequest(QUrl url);
private slots:
void downloadFile();
void cancelDownload();
void httpFinished();
void httpReadyRead();
void updateDataReadProgress(qint64 bytesRead, qint64 totalBytes);
void enableDownloadButton();
void slotAuthenticationRequired(QNetworkReply*,QAuthenticator *);
private:
QLabel *statusLabel;
QLabel *urlLabel;
QLineEdit *urlLineEdit;
QProgressDialog *progressDialog;
QPushButton *downloadButton;
QPushButton *quitButton;
QDialogButtonBox *buttonBox;
QUrl url;
QNetworkAccessManager qnam;
QNetworkReply *reply;
QFile *file;
int httpGetId;
bool httpRequestAborted;
};
1.开始下载
2.取消下载
3.预备下载
4.下载完成
5.进度回调
等
实现为:
void HttpWindow::startRequest(QUrl url)
{
reply = qnam.get(QNetworkRequest(url));
connect(reply, SIGNAL(finished()),
this, SLOT(httpFinished()));
connect(reply, SIGNAL(readyRead()),
this, SLOT(httpReadyRead()));
connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
this, SLOT(updateDataReadProgress(qint64,qint64)));
}
该函数主要针对给定url绑定事件{
reply = qnam.get(QNetworkRequest(url));
connect(reply, SIGNAL(finished()),
this, SLOT(httpFinished()));
connect(reply, SIGNAL(readyRead()),
this, SLOT(httpReadyRead()));
connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
this, SLOT(updateDataReadProgress(qint64,qint64)));
}
void HttpWindow::downloadFile()
{
url = urlLineEdit->text();
QFileInfo fileInfo(url.path());
QString fileName = fileInfo.fileName();
fileName = "downloadfile.dat";
if(fileName.isEmpty())
fileName = "index.html";
if(QFile::exists(fileName)) {
if (QMessageBox::question(this, tr("HTTP"),
tr("There already exists a file called %1 in "
"the current directory. Overwrite?").arg(fileName),
QMessageBox::Yes|QMessageBox::No, QMessageBox::No)
== QMessageBox::No)
return;
QFile::remove(fileName);
}
file = new QFile(fileName);
if (!file->open(QIODevice::WriteOnly)) {
QMessageBox::information(this, tr("HTTP"),
tr("Unable to save the file %1: %2.")
.arg(fileName).arg(file->errorString()));
delete file;
file = 0;
return;
}
progressDialog->setWindowTitle(tr("HTTP"));
progressDialog->setLabelText(tr("Downloading %1.").arg(fileName));
downloadButton->setEnabled(false);
// schedule the request
httpRequestAborted = false;
startRequest(url);
}
当点击下载的时候,会执行该函数{
url = urlLineEdit->text();
QFileInfo fileInfo(url.path());
QString fileName = fileInfo.fileName();
fileName = "downloadfile.dat";
if(fileName.isEmpty())
fileName = "index.html";
if(QFile::exists(fileName)) {
if (QMessageBox::question(this, tr("HTTP"),
tr("There already exists a file called %1 in "
"the current directory. Overwrite?").arg(fileName),
QMessageBox::Yes|QMessageBox::No, QMessageBox::No)
== QMessageBox::No)
return;
QFile::remove(fileName);
}
file = new QFile(fileName);
if (!file->open(QIODevice::WriteOnly)) {
QMessageBox::information(this, tr("HTTP"),
tr("Unable to save the file %1: %2.")
.arg(fileName).arg(file->errorString()));
delete file;
file = 0;
return;
}
progressDialog->setWindowTitle(tr("HTTP"));
progressDialog->setLabelText(tr("Downloading %1.").arg(fileName));
downloadButton->setEnabled(false);
// schedule the request
httpRequestAborted = false;
startRequest(url);
}
获取url链接,生成本地文件,...
void HttpWindow::cancelDownload()
{
statusLabel->setText(tr("Download canceled."));
httpRequestAborted = true;
reply->abort();
downloadButton->setEnabled(true);
}
终止下载,主要函数是reply->abort();{
statusLabel->setText(tr("Download canceled."));
httpRequestAborted = true;
reply->abort();
downloadButton->setEnabled(true);
}
void HttpWindow::httpFinished()
{
if (httpRequestAborted) {
if (file) {
file->close();
file->remove();
delete file;
file = 0;
}
reply->deleteLater();
progressDialog->hide();
return;
}
progressDialog->hide();
file->flush();
file->close();
QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (reply->error()) {
file->remove();
QMessageBox::information(this, tr("HTTP"),
tr("Download failed: %1.")
.arg(reply->errorString()));
downloadButton->setEnabled(true);
} else if (!redirectionTarget.isNull()) {
QUrl newUrl = url.resolved(redirectionTarget.toUrl());
if (QMessageBox::question(this, tr("HTTP"),
tr("Redirect to %1 ?").arg(newUrl.toString()),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
url = newUrl;
reply->deleteLater();
file->open(QIODevice::WriteOnly);
file->resize(0);
startRequest(url);
return;
}
} else {
QString fileName = QFileInfo(QUrl(urlLineEdit->text()).path()).fileName();
statusLabel->setText(tr("Downloaded %1 to current directory.").arg(fileName));
downloadButton->setEnabled(true);
}
reply->deleteLater();
reply = 0;
delete file;
file = 0;
}
下载结束动作{
if (httpRequestAborted) {
if (file) {
file->close();
file->remove();
delete file;
file = 0;
}
reply->deleteLater();
progressDialog->hide();
return;
}
progressDialog->hide();
file->flush();
file->close();
QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (reply->error()) {
file->remove();
QMessageBox::information(this, tr("HTTP"),
tr("Download failed: %1.")
.arg(reply->errorString()));
downloadButton->setEnabled(true);
} else if (!redirectionTarget.isNull()) {
QUrl newUrl = url.resolved(redirectionTarget.toUrl());
if (QMessageBox::question(this, tr("HTTP"),
tr("Redirect to %1 ?").arg(newUrl.toString()),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
url = newUrl;
reply->deleteLater();
file->open(QIODevice::WriteOnly);
file->resize(0);
startRequest(url);
return;
}
} else {
QString fileName = QFileInfo(QUrl(urlLineEdit->text()).path()).fileName();
statusLabel->setText(tr("Downloaded %1 to current directory.").arg(fileName));
downloadButton->setEnabled(true);
}
reply->deleteLater();
reply = 0;
delete file;
file = 0;
}
void HttpWindow::httpReadyRead()
{
// this slot gets called every time the QNetworkReply has new data.
// We read all of its new data and write it into the file.
// That way we use less RAM than when reading it at the finished()
// signal of the QNetworkReply
if (file)
file->write(reply->readAll());
}
写文件回调{
// this slot gets called every time the QNetworkReply has new data.
// We read all of its new data and write it into the file.
// That way we use less RAM than when reading it at the finished()
// signal of the QNetworkReply
if (file)
file->write(reply->readAll());
}
void HttpWindow::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
{
if (httpRequestAborted)
return;
progressDialog->setMaximum(totalBytes);
progressDialog->setValue(bytesRead);
}
进度回调{
if (httpRequestAborted)
return;
progressDialog->setMaximum(totalBytes);
progressDialog->setValue(bytesRead);
}
要点:
1.针对QNetReply绑定需要的信号和槽
2.实现需要的槽函数