BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Qt5 Tutorial QNetworkAccessManager - Downloading Files - 2020





Bookmark and Share





bogotobogo.com site search:




QNetworkAccessManager / QNetworkRequest - Downloading Files

In this tutorial, we will learn how to download a file using QNetworkAccessManager.

Note: Qt5 document

The QFtp, QUrlInfo, QHttp classes are not public anymore (QHttp has been discouraged since Qt 4.7). Use QNetworkAccessManager instead to avoid binary breaks in the future. Programs that require raw FTP/HTTP streams, can use the compatibility add-ons QtFtp and QtHttp which provides the QFtp and QHttp classes as they existed in Qt 4.



We'll start with Qt Console Application.

InitialExplorer.png

First, we need to add network module to our project file, QHpptDownload.pro:

QT       += core
QT       += network
QT       -= gui

TARGET = QHttpDownload
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app


SOURCES += main.cpp

Then, we want to create a new class called Downloader.

In general, this tutorial is almost the same with the one of my C++ tutorials Sockets - Server and Client using Qt : Http Download. However, this tutorial is using NetworkAccessManager instead of QHttp as recommended by Qt5.

Now, let's work on our header file, downloader.h.

We want to include <QNetworkAccessManager>, <QNetworkRequest>, <QNetworkReply>, <QUrl>, <QDateTime>, <QFile>, and <QDebug>. Then, we need to put a reference to QNetworkAccessManager as a private member.

Also, we need to emit a signal, replyFinished().

We want to declare a public function doDownload().

#ifndef DOWNLOADER_H
#define DOWNLOADER_H

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QDateTime>
#include <QFile>
#include <QDebug>


class Downloader : public QObject
{
    Q_OBJECT
public:
    explicit Downloader(QObject *parent = 0);

    void doDownload();

signals:

public slots:
    void replyFinished (QNetworkReply *reply);

private:
   QNetworkAccessManager *manager;

};

Lets move on to the implementation:

The whole process will be kick off by doDownload():

void Downloader::doDownload()
{
    manager = new QNetworkAccessManager(this);

    connect(manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(replyFinished(QNetworkReply*)));

    manager->get(QNetworkRequest(QUrl("http://bogotobogo.com")));
}

Here is the description for QNetworkAccessManager from Qt 5 document.

The QNetworkAccessManager class allows the application to send network requests and receive replies.

The Network Access API is constructed around one QNetworkAccessManager object, which holds the common configuration and settings for the requests it sends. It contains the proxy and cache configuration, as well as the signals related to such issues, and reply signals that can be used to monitor the progress of a network operation. One QNetworkAccessManager should be enough for the whole Qt application.

Once a QNetworkAccessManager object has been created, the application can use it to send requests over the network. A group of standard functions are supplied that take a request and optional data, and each return a QNetworkReply object. The returned object is used to obtain any data returned in response to the corresponding request.

The doDownload() function is called from main(), and the slot replyFinished() is the place we do whatever we want with the QNetworkReply *:

void Downloader::replyFinished (QNetworkReply *reply)
{
    if(reply->error())
    {
        qDebug() << "ERROR!";
        qDebug() << reply->errorString();
    }
    else
    {
        qDebug() << reply->header(QNetworkRequest::ContentTypeHeader).toString();
        qDebug() << reply->header(QNetworkRequest::LastModifiedHeader).toDateTime().toString();;
        qDebug() << reply->header(QNetworkRequest::ContentLengthHeader).toULongLong();
        qDebug() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        qDebug() << reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();

        QFile *file = new QFile("C:/Qt/Dummy/downloaded.txt");
        if(file->open(QFile::Append))
        {
            file->write(reply->readAll());
            file->flush();
            file->close();
        }
        delete file;
    }

    reply->deleteLater();
}

For more information on enums such as
QNetworkRequest::Attribute,
QNetworkRequest::CacheLoadControl,
and QNetworkRequest::KnownHeaders,
visit http://qt-project.org/doc/qt-5.0/qtnetwork/qnetworkrequest.html.



Here are the files used in this tutorial.


main.cpp:

#include <QCoreApplication>
#include "downloader.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    
    Downloader d;
    d.doDownload();

    return a.exec();
}

downloader.h:

#ifndef DOWNLOADER_H
#define DOWNLOADER_H

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QDateTime>
#include <QFile>
#include <QDebug>

class Downloader : public QObject
{
    Q_OBJECT
public:
    explicit Downloader(QObject *parent = 0);

    void doDownload();

signals:
    
public slots:
    void replyFinished (QNetworkReply *reply);

private:
   QNetworkAccessManager *manager;
    
};

#endif // DOWNLOADER_H

downloader.cpp:

#include "downloader.h"

Downloader::Downloader(QObject *parent) :
    QObject(parent)
{
}

void Downloader::doDownload()
{
    manager = new QNetworkAccessManager(this);

    connect(manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(replyFinished(QNetworkReply*)));

    manager->get(QNetworkRequest(QUrl("http://bogotobogo.com")));
}

void Downloader::replyFinished (QNetworkReply *reply)
{
    if(reply->error())
    {
        qDebug() << "ERROR!";
        qDebug() << reply->errorString();
    }
    else
    {
        qDebug() << reply->header(QNetworkRequest::ContentTypeHeader).toString();
        qDebug() << reply->header(QNetworkRequest::LastModifiedHeader).toDateTime().toString();
        qDebug() << reply->header(QNetworkRequest::ContentLengthHeader).toULongLong();
        qDebug() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        qDebug() << reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();

        QFile *file = new QFile("C:/Qt/Dummy/downloaded.txt");
        if(file->open(QFile::Append))
        {
            file->write(reply->readAll());
            file->flush();
            file->close();
        }
        delete file;
    }

    reply->deleteLater();
}

If we run the code:

"text/html"
"Sun Dec 23 00:11:02 2012"
0
200
"OK"

If not successful. Otherwise, it will print our error message from reply->error().

For extended version using UI and QProgressDialog, please visit Http File Download with UI and QProgressDialog.







Qt 5 Tutorial

  1. Hello World
  2. Signals and Slots
  3. Q_OBJECT Macro
  4. MainWindow and Action
  5. MainWindow and ImageViewer using Designer A
  6. MainWindow and ImageViewer using Designer B
  7. Layouts
  8. Layouts without Designer
  9. Grid Layouts
  10. Splitter
  11. QDir
  12. QFile (Basic)
  13. Resource Files (.qrc)
  14. QComboBox
  15. QListWidget
  16. QTreeWidget
  17. QAction and Icon Resources
  18. QStatusBar
  19. QMessageBox
  20. QTimer
  21. QList
  22. QListIterator
  23. QMutableListIterator
  24. QLinkedList
  25. QMap
  26. QHash
  27. QStringList
  28. QTextStream
  29. QMimeType and QMimeDatabase
  30. QFile (Serialization I)
  31. QFile (Serialization II - Class)
  32. Tool Tips in HTML Style and with Resource Images
  33. QPainter
  34. QBrush and QRect
  35. QPainterPath and QPolygon
  36. QPen and Cap Style
  37. QBrush and QGradient
  38. QPainter and Transformations
  39. QGraphicsView and QGraphicsScene
  40. Customizing Items by inheriting QGraphicsItem
  41. QGraphicsView Animation
  42. FFmpeg Converter using QProcess
  43. QProgress Dialog - Modal and Modeless
  44. QVariant and QMetaType
  45. QtXML - Writing to a file
  46. QtXML - QtXML DOM Reading
  47. QThreads - Introduction
  48. QThreads - Creating Threads
  49. Creating QThreads using QtConcurrent
  50. QThreads - Priority
  51. QThreads - QMutex
  52. QThreads - GuiThread
  53. QtConcurrent QProgressDialog with QFutureWatcher
  54. QSemaphores - Producer and Consumer
  55. QThreads - wait()
  56. MVC - ModelView with QListView and QStringListModel
  57. MVC - ModelView with QTreeView and QDirModel
  58. MVC - ModelView with QTreeView and QFileSystemModel
  59. MVC - ModelView with QTableView and QItemDelegate
  60. QHttp - Downloading Files
  61. QNetworkAccessManager and QNetworkRequest - Downloading Files
  62. Qt's Network Download Example - Reconstructed
  63. QNetworkAccessManager - Downloading Files with UI and QProgressDialog
  64. QUdpSocket
  65. QTcpSocket
  66. QTcpSocket with Signals and Slots
  67. QTcpServer - Client and Server
  68. QTcpServer - Loopback Dialog
  69. QTcpServer - Client and Server using MultiThreading
  70. QTcpServer - Client and Server using QThreadPool
  71. Asynchronous QTcpServer - Client and Server using QThreadPool
  72. Qt Quick2 QML Animation - A
  73. Qt Quick2 QML Animation - B
  74. Short note on Ubuntu Install
  75. OpenGL with QT5
  76. Qt5 Webkit : Web Browser with QtCreator using QWebView Part A
  77. Qt5 Webkit : Web Browser with QtCreator using QWebView Part B
  78. Video Player with HTML5 QWebView and FFmpeg Converter
  79. Qt5 Add-in and Visual Studio 2012
  80. Qt5.3 Installation on Ubuntu 14.04
  81. Qt5.5 Installation on Ubuntu 14.04
  82. Short note on deploying to Windows



Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







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




Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong













Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master