Reputation: 35
Hello I wrote program that should download web page and save it as a file. It does it but partially only. Have anybody encounterd such a problem?
mainwindow.cpp source file:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QNetworkAccessManager>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
netManager = new QNetworkAccessManager;
setFile("myPage");
}
MainWindow::~MainWindow()
{
netManager->deleteLater();
delete ui;
}
void MainWindow::setFile(QString fileURL)
{
QString savePath;
savePath = QString("D:/page.html");
QNetworkRequest request;
request.setUrl(QUrl(fileURL));
reply = netManager->get(request);
file = new QFile;
file->setFileName(savePath);
file->open(QIODevice::WriteOnly);
connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(onProgress(qint64,qint64)));
connect(netManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*)));
connect(reply, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(reply, SIGNAL(finished()), this, SLOT(onReplyFinished()));
}
void MainWindow::onProgress(qint64 bRead, qint64 bTotal)
{
qDebug(QString::number(bRead).toLatin1() + " - " + QString::number(bTotal).toLatin1());
}
void MainWindow::onFinished(QNetworkReply *reply)
{
switch (reply->error())
{
case QNetworkReply::NoError:
{
qDebug("File downloaded");
qDebug() << file->size();
}break;
default:
{
qDebug(reply->errorString().toLatin1());
}
}
if(file->isOpen())
{
file->close();
file->deleteLater();
}
}
void MainWindow::onReadyRead()
{
file->write(reply->readAll());
}
void MainWindow::onReplyFinished()
{
if(file->isOpen())
{
file->close();
file->deleteLater();
}
}
mainwindow.h header source file:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QNetworkAccessManager>
#include <QFile>
#include <QNetworkReply>
#include <QNetworkReply>
#include <QStringList>
namespace Ui
{
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void setFile(QString fileURL);
private slots:
void onFinished(QNetworkReply *);
void onProgress(qint64 bRead, qint64 bTotal);
void onReadyRead();
void onReplyFinished();
private:
Ui::MainWindow *ui;
QNetworkAccessManager *netManager;
QNetworkReply *reply;
QFile *file;
};
#endif // MAINWINDOW_H
I tried to solve it myself but after many tries I failed. I'm beginner in QT, so propably I've made a mistake somewhere, and I don't even see it. Can anybody drive me to a proper way to fix the problem?
Upvotes: 3
Views: 96
Reputation: 1313
You should put this:
connect(netManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*)));
before:
reply = netManager->get(request);
Works fine after this modification ;)
Upvotes: 1