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);
}
相关推荐
Databend19 小时前
在 AWS 中国峰会逛了一天,我在 Databend 展台看到了 Agent 数据基础设施的新思路
数据库·人工智能·agent
ClouGence2 天前
Oracle 数据同步为什么会出现数据不一致?长事务是常被忽略的原因
数据库·后端·oracle
Quz2 天前
QML Hello World 入门示例
qt
飞将2 天前
从零实现数据库(2)——HashIndex + IndexManager
数据库
Nturmoils3 天前
订单列表慢查询,先看 WHERE、ORDER BY 和 LIMIT
数据库
渣波3 天前
拒绝 SQL 焦虑!手把手带你用 NestJS + Prisma + DTO 写出“防弹”级后端代码
javascript·数据库·后端
倔强的石头_4 天前
KingbaseES 新版MySQL 兼容版体验:旧版迁移 + 功能实测
数据库
xcyxiner5 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner6 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner6 天前
DicomViewer (添加模型类)3
qt