1、新建一个Qt Gui应用,项目名称为http,基类选择为QMainWindow,类名设置为MainWindow。
2、在http.pro文件中的QT += core gui后添加\ network,或者直接添加QT += network。
3、在mainwindow.ui文件中分别拖入label控件、lineEdit控件、pushButton控件以及progressBar控件,如下。
4、在mainwindow.h头文件中添加以下代码,同时添加#include<QtNetwork>
public:
void startRequest(QUrl url); private:
QNetworkReply *reply;
QUrl url;//存储网络地址
QFile *file;//文件指针 private slots:
void on_pushButton_clicked();
void httpFinished();
void httpReadyRead();
void updateDataReadProgress(qint64, qint64);
5、在mainwindow.cpp源文件的构造函数中添加代码
ui->progressBar->hide();
同时,在mainwindow.cpp源文件中添加以下函数代码
void MainWindow::on_pushButton_clicked()
{
url = ui->lineEdit->text();
QFileInfo info(url.path());
QString fileName(info.fileName());
if (fileName.isEmpty()) fileName = "index.html";
file = new QFile(fileName);
if(!file->open(QIODevice::WriteOnly))//打开成功返回true,否则返回false
{
qDebug() << "file open error";
delete file;
file = ;
return;
}
startRequest(url);
ui->progressBar->setValue();
ui->progressBar->show();
} void MainWindow::startRequest(QUrl url)
{
QNetworkAccessManager *manager;
manager = new QNetworkAccessManager(this);
reply = manager->get(QNetworkRequest(url));
connect(reply, SIGNAL(readyRead()), this, SLOT(httpReadyRead()));//readyRead()信号继承自QIODevice类,每当有新的数据可以读取时,都会发射该信号
connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(updateDataReadProgress(qint64, qint64)));//每当网络请求的下载进度更新时都会发射downloadProgress()信号
connect(reply, SIGNAL(finished()), this, SLOT(httpFinished()));//每当应答处理结束时,都会发射finished()信号
} void MainWindow::httpReadyRead()
{
if (file)
file->write(reply->readAll());//如果创建了文件,则读取返回的所有数据,然后写入到文件。
} void MainWindow::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
{
ui->progressBar->setMaximum(totalBytes);
ui->progressBar->setValue(bytesRead);
} void MainWindow::httpFinished()
{
ui->progressBar->hide();
file->flush(); //文件刷新
file->close();//文件关闭
reply->deleteLater();
reply = ;
delete file;
file = ;
}
6、运行,输入文件下载地址,点击下载后界面显示如下
7、文件自动下载到工程根目录下