Qt - Downloading file from URL
May 18, 2014 at 12:53pm UTC
Hello.
I'm really new to Qt. I learnt GUI ~2 weeks. Now, I'm with networking.
Based on the Qt examples (almost a copy), I made this class:
(HEADER)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#ifndef QDOWNLOADER_HPP
#define QDOWNLOADER_HPP
#include <QObject>
#include <QByteArray>
#include <QString>
#include <QtNetwork>
#include <QDir>
#include <QFile>
class QDownloader : public QObject
{
Q_OBJECT
public :
explicit QDownloader(QObject *parent = 0);
QDownloader(const QString url, QObject* parent = 0, const QDir dir = QDir::currentPath());
QString data() const ;
signals:
void downloaded();
public slots:
void download(const QString url);
private slots:
void downloaded_file(QNetworkReply* reply);
private :
QNetworkAccessManager manager;
QByteArray downloaded_data;
};
#endif // QDOWNLOADER_HPP
(IMPLEMENTATIONS)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include "qdownloader.hpp"
QDownloader::QDownloader(QObject *parent) :
QObject(parent)
{
}
QDownloader::QDownloader(const QString url, QObject* parent, const QDir dir) :
QObject(parent)
{
this ->download(url);
}
void QDownloader::download(const QString url)
{
connect(&manager, SIGNAL(finished(QNetworkReply*)), SLOT(downloaded_file(QNetworkReply*)));
QNetworkRequest request(url);
manager.get(request);
}
void QDownloader::downloaded_file(QNetworkReply *reply)
{
this ->downloaded_data = reply->readAll();
reply->deleteLater();
emit downloaded();
}
QString QDownloader::data() const
{
return QString(this ->downloaded_data);
}
And using like that:
1 2 3 4 5 6 7 8 9 10
#include <QCoreApplication>
#include <QDebug>
#include "C:/cpp/libs/qdownloader.hpp"
int main(int argc, char * argv[])
{
QCoreApplication app(argc, argv);
QDownloader a("http://www.google.com/robots.txt" );
qDebug() << a.data();
return app.exec();
}
But the program output is that:
http://s28.postimg.org/idb2jbtzh/error.png
What am I doing wrong? How to fix it?
May 19, 2014 at 4:10pm UTC
Anyone?
May 19, 2014 at 5:40pm UTC
I think that those are just warnings. Notice that the last line is "".
The problem is that a network request is not made until the event loop executes (line 9 in main.cpp). So you get an empty QString at line 8 (the "").
Try adding a qDebug() as follows:
1 2 3 4 5 6 7
void QDownloader::downloaded_file(QNetworkReply *reply)
{
this ->downloaded_data = reply->readAll();
qDebug() << downloaded_data; // should get some output here
reply->deleteLater();
emit downloaded();
}
Topic archived. No new replies allowed.