Qt5 Tutorial Http File Download with QNetworkRequest and Simple UI - 2020
In this tutorial, we will learn how to download a file using QNetworkRequest.
The QNetworkRequest class holds a request to be sent with QNetworkAccessManager.
QNetworkRequest is part of the Network Access API and is the class holding the information necessary to send a request over the network. It contains a URL and some ancillary information that can be used to modify the request.
This version is a continuation from Downloading files with QNetworkAccessManager by adding UI and QProcessDialog as shown in the pictures below.
We'll start with Qt Gui Application.
First, we need to add network module to our project file, HttpDownload.pro:
QT += network DEFINES += QT_NO_SSL
Though we do not have the code for SSL, but I added it to the .pro just to demonstrate how we set Macro.
Here is an initial design of dialog for Http file download.
Also, we setup a few slots:
private slots: void on_downloadButton_clicked(); void on_quitButton_clicked(); void on_urlEdit_returnPressed();
For the last two slots, it's obvious what to do:
void HttpDownload::on_quitButton_clicked() { this->close(); } void HttpDownload::on_urlEdit_returnPressed() { on_downloadButton_clicked(); }
Note that the action from return pressed is deferred to on_downloadButton_clicked() slot. So, the key coding will be what to do when download button is clicked.
When download button is pressed, we know the url. So, we'll do construct QNetworkRequest object with the url:
QNetworkRequest(url);
We need to somehow use "GET" method, and it's available via QNetworkAccessManager Class. The class has couple of methods we may need:
- QNetworkReply * QNetworkAccessManager::get(const QNetworkRequest & request)
This method posts a request to obtain the contents of the target request and returns a new QNetworkReply object opened for reading which emits the readyRead() signal whenever new data arrives. - void QNetworkReply::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) - signal
This signal is emitted to indicate the progress of the download part of this network request, if there's any. If there's no download associated with this request, this signal will be emitted once with 0 as the value of both bytesReceived and bytesTotal.
The bytesReceived parameter indicates the number of bytes received, while bytesTotal indicates the total number of bytes expected to be downloaded. If the number of bytes to be downloaded is not known, bytesTotal will be -1. The download is finished when bytesReceived is equal to bytesTotal. At that time, bytesTotal will not be -1. - void QNetworkReply::finished() - signal
This signal is emitted when the reply has finished processing. After this signal is emitted, there will be no more updates to the reply's data or metadata.
Unless close() has been called, the reply will be still be opened for reading, so the data can be retrieved by calls to read() or readAll(). In particular, if no calls to read() were made as a result of readyRead(), a call to readAll() will retrieve the full contents in a QByteArray. This signal is emitted in tandem with QNetworkAccessManager::finished() where that signal's reply parameter is this object.
Before we do any coding for QNetworkReply, we may want to read this:
- The QNetworkReply class contains the data and headers for a request sent with QNetworkAccessManager
- The QNetworkReply contains a URL and headers (both in parsed and raw form), some information about the reply's state and the contents of the reply itself.
- QNetworkReply is a sequential-access QIODevice, which means that once data is read from the object, it no longer kept by the device. It is therefore the application's responsibility to keep this data if it needs to. Whenever more data is received from the network and processed, the
- readyRead() signal is emitted.
- The downloadProgress() signal is also emitted when data is received.
Here is the skeleton of the code:
void HttpDownload::on_downloadButton_clicked() { // get url url = (ui->urlEdit->text()); // get() method posts a request // to obtain the contents of the target request // and returns a new QNetworkReply object // opened for reading which emits // the readyRead() signal whenever new data arrives. reply = manager->get(QNetworkRequest(url)); // Whenever more data is received from the network, // this readyRead() signal is emitted connect(reply, SIGNAL(readyRead()), this, SLOT(httpReadyRead())); }
In this tutorial, I could not get the file size before the download, I mean, not every site I tried. The progressDialog is failing to display the progress in such a case.
Here are my tries:
- Using slot :
void HttpDownload::updateDownloadProgress(qint64 bytesRead, qint64 totalBytes)
for the signalconnect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(updateDownloadProgress(qint64,qint64)));
where the reply is an QNetworkReply object defined as:reply = manager->get(QNetworkRequest(url));
The totalBytes is -1 and QT doc says:
bytesTotal indicates the total number of bytes expected to be downloaded. If the number of bytes to be downloaded is not known, bytesTotal will be -1.
So, it sets the max value for the progress bar -1 which is not right:progressDialog->setMaximum(totalBytes);
- Used QFileInfo() to get the file size:
QFileInfo fileInfo(url.path()); fileSize = fileInfo.size();
But this returns 0, probably it evalues 0 from the QVariant::invalid. - The last approach is to use
reply->header(QNetworkRequest::ContentLengthHeader).toULongLong();
It gives me 0, probably because of the same reason as in my try #2.
I'll fix this problem as soon as I figured out.
Or if you know the answer, please give me an advice "contactus@bogotobogo.com"
In this tutorial, I'm using #1 approach, though internally, Qt is probably, doing the same.
Project zip file: HttpWindow.zip
main.cpp
#include "httpdownload.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); HttpDownload w; w.setWindowTitle("Http Download"); w.show(); return a.exec(); }
httpdownload.h
#ifndef HTTPDOWNLOAD_H #define HTTPDOWNLOAD_H #include <QDialog> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QUrl> #include <QProgressDialog> #include <QFile> #include <QFileInfo> #include <QDir> #include <QMessageBox> namespace Ui { class HttpDownload; } class HttpDownload : public QDialog { Q_OBJECT public: explicit HttpDownload(QWidget *parent = 0); ~HttpDownload(); public: void startRequest(QUrl url); private slots: void on_downloadButton_clicked(); void on_quitButton_clicked(); void on_urlEdit_returnPressed(); // slot for readyRead() signal void httpReadyRead(); // slot for finished() signal from reply void httpDownloadFinished(); // slot for downloadProgress() void updateDownloadProgress(qint64, qint64); void enableDownloadButton(); void cancelDownload(); private: Ui::HttpDownload *ui; QUrl url; QNetworkAccessManager *manager; QNetworkReply *reply; QProgressDialog *progressDialog; QFile *file; bool httpRequestAborted; qint64 fileSize; }; #endif // HTTPDOWNLOAD_H
httpdownload.cpp
#include "httpdownload.h" #include "ui_httpdownload.h" HttpDownload::HttpDownload(QWidget *parent) : QDialog(parent), ui(new Ui::HttpDownload) { ui->setupUi(this); ui->urlEdit->setText("http://qt.com"); ui->statusLabel->setWordWrap(true); ui->downloadButton->setDefault(true); ui->quitButton->setAutoDefault(false); progressDialog = new QProgressDialog(this); connect(ui->urlEdit, SIGNAL(textChanged(QString)), this, SLOT(enableDownloadButton())); connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload())); } HttpDownload::~HttpDownload() { delete ui; } void HttpDownload::on_downloadButton_clicked() { manager = new QNetworkAccessManager(this); // get url url = (ui->urlEdit->text()); QFileInfo fileInfo(url.path()); QString fileName = fileInfo.fileName(); 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; } // used for progressDialog // This will be set true when canceled from progress dialog httpRequestAborted = false; progressDialog->setWindowTitle(tr("HTTP")); progressDialog->setLabelText(tr("Downloading %1.").arg(fileName)); // download button disabled after requesting download ui->downloadButton->setEnabled(false); startRequest(url); } void HttpDownload::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()); } void HttpDownload::updateDownloadProgress(qint64 bytesRead, qint64 totalBytes) { if (httpRequestAborted) return; progressDialog->setMaximum(totalBytes); progressDialog->setValue(bytesRead); } void HttpDownload::on_quitButton_clicked() { this->close(); } void HttpDownload::on_urlEdit_returnPressed() { on_downloadButton_clicked(); } void HttpDownload::enableDownloadButton() { ui->downloadButton->setEnabled(!(ui->urlEdit->text()).isEmpty()); } // During the download progress, it can be canceled void HttpDownload::cancelDownload() { ui->statusLabel->setText(tr("Download canceled.")); httpRequestAborted = true; reply->abort(); ui->downloadButton->setEnabled(true); } // When download finished or canceled, this will be called void HttpDownload::httpDownloadFinished() { // when canceled if (httpRequestAborted) { if (file) { file->close(); file->remove(); delete file; file = 0; } reply->deleteLater(); progressDialog->hide(); return; } // download finished normally progressDialog->hide(); file->flush(); file->close(); // get redirection url QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); if (reply->error()) { file->remove(); QMessageBox::information(this, tr("HTTP"), tr("Download failed: %1.") .arg(reply->errorString())); ui->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(ui->urlEdit->text()).path()).fileName(); ui->statusLabel->setText(tr("Downloaded %1 to %2.").arg(fileName).arg(QDir::currentPath())); ui->downloadButton->setEnabled(true); } reply->deleteLater(); reply = 0; delete file; file = 0; manager = 0; } // This will be called when download button is clicked void HttpDownload::startRequest(QUrl url) { // get() method posts a request // to obtain the contents of the target request // and returns a new QNetworkReply object // opened for reading which emits // the readyRead() signal whenever new data arrives. reply = manager->get(QNetworkRequest(url)); // Whenever more data is received from the network, // this readyRead() signal is emitted connect(reply, SIGNAL(readyRead()), this, SLOT(httpReadyRead())); // Also, downloadProgress() signal is emitted when data is received connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(updateDownloadProgress(qint64,qint64))); // This signal is emitted when the reply has finished processing. // After this signal is emitted, // there will be no more updates to the reply's data or metadata. connect(reply, SIGNAL(finished()), this, SLOT(httpDownloadFinished())); }
Qt 5 Tutorial
- Hello World
- Signals and Slots
- Q_OBJECT Macro
- MainWindow and Action
- MainWindow and ImageViewer using Designer A
- MainWindow and ImageViewer using Designer B
- Layouts
- Layouts without Designer
- Grid Layouts
- Splitter
- QDir
- QFile (Basic)
- Resource Files (.qrc)
- QComboBox
- QListWidget
- QTreeWidget
- QAction and Icon Resources
- QStatusBar
- QMessageBox
- QTimer
- QList
- QListIterator
- QMutableListIterator
- QLinkedList
- QMap
- QHash
- QStringList
- QTextStream
- QMimeType and QMimeDatabase
- QFile (Serialization I)
- QFile (Serialization II - Class)
- Tool Tips in HTML Style and with Resource Images
- QPainter
- QBrush and QRect
- QPainterPath and QPolygon
- QPen and Cap Style
- QBrush and QGradient
- QPainter and Transformations
- QGraphicsView and QGraphicsScene
- Customizing Items by inheriting QGraphicsItem
- QGraphicsView Animation
- FFmpeg Converter using QProcess
- QProgress Dialog - Modal and Modeless
- QVariant and QMetaType
- QtXML - Writing to a file
- QtXML - QtXML DOM Reading
- QThreads - Introduction
- QThreads - Creating Threads
- Creating QThreads using QtConcurrent
- QThreads - Priority
- QThreads - QMutex
- QThreads - GuiThread
- QtConcurrent QProgressDialog with QFutureWatcher
- QSemaphores - Producer and Consumer
- QThreads - wait()
- MVC - ModelView with QListView and QStringListModel
- MVC - ModelView with QTreeView and QDirModel
- MVC - ModelView with QTreeView and QFileSystemModel
- MVC - ModelView with QTableView and QItemDelegate
- QHttp - Downloading Files
- QNetworkAccessManager and QNetworkRequest - Downloading Files
- Qt's Network Download Example - Reconstructed
- QNetworkAccessManager - Downloading Files with UI and QProgressDialog
- QUdpSocket
- QTcpSocket
- QTcpSocket with Signals and Slots
- QTcpServer - Client and Server
- QTcpServer - Loopback Dialog
- QTcpServer - Client and Server using MultiThreading
- QTcpServer - Client and Server using QThreadPool
- Asynchronous QTcpServer - Client and Server using QThreadPool
- Qt Quick2 QML Animation - A
- Qt Quick2 QML Animation - B
- Short note on Ubuntu Install
- OpenGL with QT5
- Qt5 Webkit : Web Browser with QtCreator using QWebView Part A
- Qt5 Webkit : Web Browser with QtCreator using QWebView Part B
- Video Player with HTML5 QWebView and FFmpeg Converter
- Qt5 Add-in and Visual Studio 2012
- Qt5.3 Installation on Ubuntu 14.04
- Qt5.5 Installation on Ubuntu 14.04
- Short note on deploying to Windows
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization