Qt HTTP下载数据

添加头文件:

cpp 复制代码
#include    <QNetworkAccessManager>
#include    <QNetworkReply>
#include    <QUrl>
#include    <QDesktopServices>

创建对象:

cpp 复制代码
QNetworkAccessManager networkManager;//网络管理
    QNetworkReply *reply;   //网络响应
    QFile *downloadedFile;//下载保存的临时文件

输入url地址:

cpp 复制代码
QUrl newUrl = QUrl::fromUserInput(urlSpec);//URL地址
复制代码
创建临时文件:
cpp 复制代码
downloadedFile =new QFile(fullFileName);
if (!downloadedFile->open(QIODevice::WriteOnly))
    {
        QMessageBox::information(this, tr("错误"),"临时文件打开错误");
复制代码
发送请求,创建网络响应:
cpp 复制代码
reply = networkManager.get(QNetworkRequest(newUrl));

连接信号与槽:

cpp 复制代码
connect(reply, SIGNAL(finished()), this, SLOT(on_finished()));
    connect(reply, SIGNAL(readyRead()), this, SLOT(on_readyRead()));
    connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
            this, SLOT(on_downloadProgress(qint64,qint64)));


void MainWindow::on_finished()
{//网络响应结束
    QFileInfo fileInfo;
    fileInfo.setFile(downloadedFile->fileName());

    downloadedFile->close();
    delete downloadedFile;
    downloadedFile = Q_NULLPTR;

    reply->deleteLater(); //
    reply = Q_NULLPTR;

    if (ui->checkOpen->isChecked())//打开下载的文件
        QDesktopServices::openUrl(QUrl::fromLocalFile(fileInfo.absoluteFilePath()));

    ui->btnDownload->setEnabled(true);
}

void MainWindow::on_readyRead()
{//读取下载的数据
    downloadedFile->write(reply->readAll());
}

void MainWindow::on_downloadProgress(qint64 bytesRead, qint64 totalBytes)
{//下载进程
    ui->progressBar->setMaximum(totalBytes);
    ui->progressBar->setValue(bytesRead);
}
相关推荐
VX:Fegn0895几秒前
计算机毕业设计|基于Java人力资源管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·课程设计
siriuuus3 分钟前
Redis 安装、多实例部署、主从复制及 Cluster 实践
数据库·redis·centos
路痴楷4 分钟前
无法定位程序输入点问题
c++·qt·visual studio
Polaris_GQ18 分钟前
Navicat连接Oracle数据库报错:12514问题
数据库
Source.Liu29 分钟前
【LibreCAD】 RS_Units 类完整解析
c++·qt·rust
老华带你飞30 分钟前
健身房|基于springboot + vue健身房管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
JIngJaneIL35 分钟前
基于Java酒店预约系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
编程小Y1 小时前
php.ini 的核心作用与全面解析
开发语言·php
曹牧1 小时前
Java:List<Map<String, String>>转换为字符串
java·开发语言·windows
我是一棵无人问荆的小草1 小时前
编码演变史
开发语言·c++