找回密码
 立即注册
  • QQ空间
  • 回复
  • 收藏

Qt官方示例-Http

admin 2019-11-7 16:46 167人围观 Qt相关


通过get接口对url资源下载,并显示下载进度。



0x00 Http请求

void HttpWindow::startRequest(const QUrl &requestedUrl)
{
...
reply = qnam.get(QNetworkRequest(url));
connect(reply,&QNetworkReply::finished,this,&HttpWindow::httpFinished);
connect(reply,&QIODevice::readyRead,this,&HttpWindow::httpReadyRead);

ProgressDialog *progressDialog =newProgressDialog(url,this);
progressDialog->setAttribute(Qt::WA_DeleteOnClose);
connect(progressDialog,&QProgressDialog::canceled,this,&HttpWindow::cancelDownload);
connect(reply,&QNetworkReply::downloadProgress, progressDialog,&ProgressDialog::networkReplyProgress);
connect(reply,&QNetworkReply::finished, progressDialog,&ProgressDialog::hide);
...
}

0x01 下载进度


  使用以下接口获取下载进度。
void QNetworkReply::downloadProgress(qint64 bytesReceived,
qint64 bytesTotal);



0x02 网络验证(如有需要)


  绑定authenticationRequired信号:
connect(&qnam,&QNetworkAccessManager::authenticationRequired,
this,&HttpWindow::slotAuthenticationRequired);

  验证动作:
oid HttpWindow::slotAuthenticationRequired(QNetworkReply *, QAuthenticator *authenticator)
{
...
// Did the URL have information? Fill the UI
// This is only relevant if the URL-supplied credentials were wrong
ui.userEdit->setText(url.userName());
ui.passwordEdit->setText(url.password());

if(authenticationDialog.exec()== QDialog::Accepted){
authenticator->setUser(ui.userEdit->text());
authenticator->setPassword(ui.passwordEdit->text());
}
}

0x03 关于更多


  • 在QtCreator软件可以找到:



  • 或在以下Qt安装目录找到
C:\Qt\{你的Qt版本}\Examples\{你的Qt版本}\network\http

  • 相关链接
https://doc.qt.io/qt-5/qtnetwork-http-example.html

  • Qt君公众号回复『Qt示例』获取更多内容。

----------------------------------------------------------------------------------------------------------------------
我们尊重原创,也注重分享,文章来源于微信公众号:Qt君,建议关注公众号查看原文。如若侵权请联系qter@qter.org。
----------------------------------------------------------------------------------------------------------------------

鲜花

握手

雷人

路过

鸡蛋

yafeilinux和他的朋友们微信公众号二维码

微信公众号

专注于Qt嵌入式Linux开发等。扫一扫立即关注。

Qt开源社区官方QQ群二维码

QQ交流群

欢迎加入QQ群大家庭,一起讨论学习!

我有话说......