Qt官方示例-Http

經過get接口對url資源下載,並顯示下載進度。

main_page

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 = new ProgressDialog(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 下載進度

  使用如下接口獲取下載進度html

void QNetworkReply::downloadProgress(qint64 bytesReceived, 
                                     qint64 bytesTotal);

main_page

0x02 網絡驗證(若有須要)

  綁定authenticationRequired信號:網絡

connect(&qnam, &QNetworkAccessManager::authenticationRequired,
        this, &HttpWindow::slotAuthenticationRequired);

  驗證動做:ide

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軟件能夠找到:

what_find

  • 或在如下Qt安裝目錄找到
C:\Qt\{你的Qt版本}\Examples\{你的Qt版本}\network\http
  • 相關連接
https://doc.qt.io/qt-5/qtnetwork-http-example.html
  • Qt君公衆號回覆『Qt示例』獲取更多內容。
相關文章
相關標籤/搜索