C C++最全Qt 之 HTTP 请求下载(支持断点续传)_qt http下载(3),大牛整理

img
img

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

    m_reply = m_networkManager->get(request);

    connect(m_reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(onDownloadProgress(qint64, qint64)));
    connect(m_reply, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    connect(m_reply, SIGNAL(finished()), this, SLOT(onFinished()));
    connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError)));
}   

}

// 下载进度信息;
void DownLoadManager::onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
if (!m_isStop)
{
m_bytesReceived = bytesReceived;
m_bytesTotal = bytesTotal;
// 更新下载进度;(加上 m_bytesCurrentReceived 是为了断点续传时之前下载的字节)
emit signalDownloadProcess(m_bytesReceived + m_bytesCurrentReceived, m_bytesTotal + m_bytesCurrentReceived);
}
}

// 获取下载内容,保存到文件中;
void DownLoadManager::onReadyRead()
{
if (!m_isStop)
{
QFile file(m_fileName);
if (file.open(QIODevice::WriteOnly | QIODevice::Append))
{
file.write(m_reply->readAll());
}
file.close();
}
}

// 下载完成;
void DownLoadManager::onFinished()
{
m_isStop = true;
// http请求状态码;
QVariant statusCode = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

if (m_reply->error() == QNetworkReply::NoError)
{
    // 重命名临时文件;
    QFileInfo fileInfo(m_fileName);
    if (fileInfo.exists())
    {
        int index = m_fileName.lastIndexOf(DOWNLOAD_FILE_SUFFIX);
        QString realName = m_fileName.left(index);
        QFile::rename(m_fileName, realName);
    }
}
else
{
    // 有错误输出错误;
    QString strError = m_reply->errorString();
    qDebug() << "\_\_\_\_\_\_\_\_\_\_" + strError;
}

emit signalReplyFinished(statusCode.toInt());

}

// 下载过程中出现错误,关闭下载,并上报错误,这里未上报错误类型,可自己定义进行上报;
void DownLoadManager::onError(QNetworkReply::NetworkError code)
{
QString strError = m_reply->errorString();
qDebug() << “__________” + strError;

closeDownload();
emit signalDownloadError();

}

// 停止下载工作;
void DownLoadManager::stopWork()
{
m_isStop = true;
if (m_reply != NULL)
{
disconnect(m_reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(onDownloadProgress(qint64, qint64)));
disconnect(m_reply, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
disconnect(m_reply, SIGNAL(finished()), this, SLOT(onFinished()));
disconnect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError)));
m_reply->abort();
m_reply->deleteLater();
m_reply = NULL;
}
}

// 暂停下载按钮被按下,暂停当前下载;
void DownLoadManager::stopDownload()
{
// 这里m_isStop变量为了保护多次点击暂停下载按钮,导致m_bytesCurrentReceived 被不停累加;
if (!m_isStop)
{
//记录当前已经下载字节数
m_bytesCurrentReceived += m_bytesReceived;
stopWork();
}
}

// 重置参数;
void DownLoadManager::reset()
{
m_bytesCurrentReceived = 0;
m_bytesReceived = 0;
m_bytesTotal = 0;
}

// 删除文件;
void DownLoadManager::removeFile(QString fileName)
{
// 删除已下载的临时文件;
QFileInfo fileInfo(fileName);
if (fileInfo.exists())
{
QFile::remove(fileName);
}
}

// 停止下载按钮被按下,关闭下载,重置参数,并删除下载的临时文件;
void DownLoadManager::closeDownload()
{
stopWork();
reset();
removeFile(m_fileName);
}


### 2、MyHttpDownload



#include “myhttpdownload.h”
#include “downloadmanager.h”
#include

#define UNIT_KB 1024 //KB
#define UNIT_MB 1024*1024 //MB
#define UNIT_GB 1024*1024*1024 //GB

#define TIME_INTERVAL 300 //0.3s

MyHttpDownload::MyHttpDownload(QWidget *parent)
QWidget(parent)
, m_downloadManager(NULL)
, m_url(“”)
, m_timeInterval(0)
, m_currentDownload(0)
, m_intervalDownload(0)
{
ui.setupUi(this);
initWindow();
}

MyHttpDownload::~MyHttpDownload()
{

}

void MyHttpDownload::initWindow()
{
ui.progressBar->setValue(0);
connect(ui.pButtonStart, SIGNAL(clicked()), this, SLOT(onStartDownload()));
connect(ui.pButtonStop, SIGNAL(clicked()), this, SLOT(onStopDownload()));
connect(ui.pButtonClose, SIGNAL(clicked()), this, SLOT(onCloseDownload()));
// 进度条设置样式;
ui.progressBar->setStyleSheet("
QProgressBar
{
border-width: 0 10 0 10;
border-left: 1px, gray;
border-right: 1px, gray;
border-image:url(:/Resources/progressbar_back.png);
}
QProgressBar::chunk
{
border-width: 0 10 0 10;
border-image:url(:/Resources/progressbar.png);
}");
}

// 开始下载;
void MyHttpDownload::onStartDownload()
{
// 从界面获取下载链接;
m_url = ui.downloadUrl->text();
if (m_downloadManager == NULL)
{
m_downloadManager = new DownLoadManager(this);
connect(m_downloadManager , SIGNAL(signalDownloadProcess(qint64, qint64)), this, SLOT(onDownloadProcess(qint64, qint64)));
connect(m_downloadManager, SIGNAL(signalReplyFinished(int)), this, SLOT(onReplyFinished(int)));
}

// 这里先获取到m\_downloadManager中的url与当前的m\_url 对比,如果url变了需要重置参数,防止文件下载不全;
QString url = m_downloadManager->getDownloadUrl();
if (url != m_url)
{
    m_downloadManager->reset();
}
m_downloadManager->setDownInto(true);
m_downloadManager->downloadFile(m_url, "F:/MyHttpDownload/MyDownloadFile.zip");
m_timeRecord.start();
m_timeInterval = 0;
ui.labelStatus->setText(QStringLiteral("正在下载"));

}

// 暂停下载;
void MyHttpDownload::onStopDownload()
{
ui.labelStatus->setText(QStringLiteral(“停止下载”));
if (m_downloadManager != NULL)
{
m_downloadManager->stopDownload();
}
ui.labelSpeed->setText(“0 KB/S”);
ui.labelRemainTime->setText(“0s”);
}

// 关闭下载;
void MyHttpDownload::onCloseDownload()
{
m_downloadManager->closeDownload();
ui.progressBar->setValue(0);
ui.labelSpeed->setText(“0 KB/S”);
ui.labelRemainTime->setText(“0s”);
ui.labelStatus->setText(QStringLiteral(“关闭下载”));
ui.labelCurrentDownload->setText(“0 B”);
ui.labelFileSize->setText(“0 B”);
}

// 更新下载进度;
void MyHttpDownload::onDownloadProcess(qint64 bytesReceived, qint64 bytesTotal)
{
// 输出当前下载进度;
// 用到除法需要注意除0错误;
qDebug() << QString(“%1”).arg(bytesReceived * 100 / bytesTotal + 1);
// 更新进度条;
ui.progressBar->setMaximum(bytesTotal);
ui.progressBar->setValue(bytesReceived);

// m\_intervalDownload 为下次计算速度之前的下载字节数;
m_intervalDownload += bytesReceived - m_currentDownload;
m_currentDownload = bytesReceived;

uint timeNow = m_timeRecord.elapsed();

// 超过0.3s更新计算一次速度;
if (timeNow - m_timeInterval > TIME_INTERVAL)
{
    qint64 ispeed = m_intervalDownload * 1000 / (timeNow - m_timeInterval);
    QString strSpeed = transformUnit(ispeed, true);
    ui.labelSpeed->setText(strSpeed);
    // 剩余时间;
    qint64 timeRemain = (bytesTotal - bytesReceived) / ispeed;
    ui.labelRemainTime->setText(transformTime(timeRemain));

    ui.labelCurrentDownload->setText(transformUnit(m_currentDownload));
    ui.labelFileSize->setText(transformUnit(bytesTotal));

    m_intervalDownload = 0;
    m_timeInterval = timeNow;
}

}

// 下载完成;
void MyHttpDownload::onReplyFinished(int statusCode)
{
// 根据状态码判断当前下载是否出错;
if (statusCode >= 200 && statusCode < 400)
{
qDebug() << “Download Failed”;
}
else
{
qDebug() << “Download Success”;
}
}

// 转换单位;
QString MyHttpDownload::transformUnit(qint64 bytes , bool isSpeed)
{
QString strUnit = " B";
if (bytes <= 0)
{
bytes = 0;
}
else if (bytes < UNIT_KB)
{
}
else if (bytes < UNIT_MB)
{
bytes /= UNIT_KB;
strUnit = " KB";
}
else if (bytes < UNIT_GB)
{
bytes /= UNIT_MB;
strUnit = " MB";
}
else if (bytes > UNIT_GB)
{
bytes /= UNIT_GB;
strUnit = " GB";
}

if (isSpeed)
{
    strUnit += "/S";
}
return QString("%1%2").arg(bytes).arg(strUnit);

}

// 转换时间;
QString MyHttpDownload::transformTime(qint64 seconds)
{
QString strValue;
QString strSpacing(" “);
if (seconds <= 0)
{
strValue = QString(”%1s").arg(0);
}
else if (seconds < 60)

img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上C C++开发知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

如果你需要这些资料,可以戳这里获取

.arg(0);
}
else if (seconds < 60)

[外链图片转存中…(img-azTaxD0I-1715696759172)]
[外链图片转存中…(img-4CmqYc2f-1715696759173)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上C C++开发知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

如果你需要这些资料,可以戳这里获取

  • 19
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值