Client HTTP
Esempio di un semplice client HTTP.
Questo esempio mostra come un semplice client HTTP possa recuperare file da host remoti.

Il lavoro principale di questo esempio viene svolto nella classe HttpWindow. Ci concentreremo quindi su quella.
QNetworkRequest networkRequest(url);
networkRequest.setTcpKeepAliveIdleTimeBeforeProbes(20s);
networkRequest.setTcpKeepAliveIntervalBetweenProbes(2s);
networkRequest.setTcpKeepAliveProbeCount(5);A partire da Qt 6.11, è possibile specificare esplicitamente i parametri di keepalive TCP per un QNetworkRequest. Nel frammento di codice sopra riportato, sovrascriviamo i valori predefiniti utilizzati da QNetworkAccessManager per adottare una strategia più aggressiva. Ciò può essere utile, ad esempio, per il rilevamento precoce di blocchi di rete causati da modifiche alla rete su Linux. In questo esempio specifico, la connessione verrà chiusa dopo trenta secondi di inattività.
reply.reset(qnam.get(networkRequest));Utilizzando ` QNetworkAccessManager`, avviamo il download di una risorsa indicata da ` url`. Se non avete familiarità con questa funzione o con la funzione utilizzata, ` QNetworkAccessManager::get()`, o se desiderate semplicemente approfondirne i dettagli, consultate la relativa documentazione e quella relativa a ` QNetworkReply ` e ` QNetworkRequest`.
connect(reply.get(), &QNetworkReply::finished, this, &HttpWindow::httpFinished);
connect(reply.get(), &QIODevice::readyRead, this, &HttpWindow::httpReadyRead);
#if QT_CONFIG(ssl)
connect(reply.get(), &QNetworkReply::sslErrors, this, &HttpWindow::sslErrors);
#endifIn precedenza, abbiamo collegato alcuni dei segnali della risposta agli slot della classe. Questi slot si occuperanno sia dei dati in entrata sia del completamento del download e della gestione degli errori.
connect(reply.get(), &QIODevice::readyRead, this, &HttpWindow::httpReadyRead);Per quanto riguarda la gestione dei dati in arrivo, poiché non conosciamo la dimensione massima di download di un potenziale input e non vogliamo esaurire la memoria di qualsiasi computer su cui possa essere eseguito il programma di esempio, gestiamo i dati in arrivo in QNetworkReply::readyRead() anziché in QNetworkReply::finished().
void HttpWindow::httpReadyRead()
{
// This slot gets called every time the QNetworkReply has new data.
// We read all of its new data and write it into the file.
// That way we use less RAM than when reading it at the finished()
// signal of the QNetworkReply
if (file)
file->write(reply->readAll());
}Quindi scriviamo i dati su file man mano che arrivano. È meno pratico, ma l’applicazione consumerà meno memoria nei momenti di picco!
connect(reply.get(), &QNetworkReply::sslErrors, this, &HttpWindow::sslErrors);Con il segnale QNetworkReply::sslErrors() possiamo anche gestire gli errori che potrebbero verificarsi durante l’handshake TLS quando ci si connette a siti web sicuri (ad esempio HTTPS).
void HttpWindow::sslErrors(const QList<QSslError> &errors)
{
QString errorString;
for (const QSslError &error : errors) {
if (!errorString.isEmpty())
errorString += '\n';
errorString += error.errorString();
}
if (QMessageBox::warning(this, tr("TLS Errors"),
tr("One or more TLS errors has occurred:\n%1").arg(errorString),
QMessageBox::Ignore | QMessageBox::Abort)
== QMessageBox::Ignore) {
reply->ignoreSslErrors();
}
}In questo esempio, mostriamo una finestra di dialogo all’utente in modo che possa scegliere se ignorare o meno gli errori.
QNetworkReply::NetworkError error = reply->error();
const QString &errorString = reply->errorString();
if (error != QNetworkReply::NoError) {
QFile::remove(fi.absoluteFilePath());
// For "request aborted" we handle the label and button in cancelDownload()
if (!httpRequestAborted) {
statusLabel->setText(tr("Download failed:\n%1.").arg(errorString));
downloadButton->setEnabled(true);
}
return;
}Se si verifica un errore, QNetworkReply emetterà il segnale QNetworkReply::errorOccurred(), seguito dal segnale QNetworkReply::finished(). In questo esempio, ci colleghiamo solo a quest’ultimo. Gestiamo eventuali errori nel rispettivo slot eliminando il file su cui stavamo scrivendo e visualizziamo l’errore con la nostra etichetta di stato.
connect(&qnam, &QNetworkAccessManager::authenticationRequired,
this, &HttpWindow::slotAuthenticationRequired);Se ci si connette a un sito web che utilizza l’autenticazione HTTP, supponendo di non aver fornito in anticipo le credenziali da utilizzare, è possibile gestire la mancanza delle credenziali quando il sito web le richiede. Con ` QNetworkAccessManager`, lo facciamo in uno slot collegato al segnale ` QNetworkAccessManager::authenticationRequired()`. Effettuiamo questa connessione una sola volta, nel costruttore.
void HttpWindow::slotAuthenticationRequired(QNetworkReply *, QAuthenticator *authenticator)
{
QDialog authenticationDialog;
Ui::Dialog ui;
ui.setupUi(&authenticationDialog);
authenticationDialog.adjustSize();
ui.siteDescription->setText(tr("%1 at %2").arg(authenticator->realm(), url.host()));
// 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());
}
}In questo esempio, mostriamo una finestra di dialogo in cui l’utente può inserire un nome utente e una password oppure annullare l’operazione. L’annullamento comporta il fallimento della richiesta.
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.