From 5006fddd33c32eb972f1bdc6b72acc43a3741e23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A5rten=20Nordheim?= Date: Wed, 11 Jan 2023 18:19:39 +0100 Subject: [PATCH] HTTP Example: Add proxy handling If a proxy is configured on the system then we will request credentials if needed. Task-number: QTBUG-108874 Fixes: QTBUG-106245 Pick-to: 6.5 Change-Id: Icbea491492cde4634421b1a1e722a3768d56dec8 Reviewed-by: Marc Mutz --- examples/network/http/httpwindow.cpp | 26 ++++++++++++++++++++++++++ examples/network/http/httpwindow.h | 6 ++++++ 2 files changed, 32 insertions(+) diff --git a/examples/network/http/httpwindow.cpp b/examples/network/http/httpwindow.cpp index 854873e574..f34bae0322 100644 --- a/examples/network/http/httpwindow.cpp +++ b/examples/network/http/httpwindow.cpp @@ -51,6 +51,10 @@ HttpWindow::HttpWindow(QWidget *parent) connect(&qnam, &QNetworkAccessManager::authenticationRequired, this, &HttpWindow::slotAuthenticationRequired); //! [qnam-auth-required-1] +#if QT_CONFIG(networkproxy) + connect(&qnam, &QNetworkAccessManager::proxyAuthenticationRequired, + this, &HttpWindow::slotProxyAuthenticationRequired); +#endif QFormLayout *formLayout = new QFormLayout; urlLineEdit->setClearButtonEnabled(true); @@ -277,3 +281,25 @@ void HttpWindow::sslErrors(const QList &errors) } //! [sslerrors-2] #endif + +#if QT_CONFIG(networkproxy) +void HttpWindow::slotProxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator) +{ + QDialog authenticationDialog; + Ui::Dialog ui; + ui.setupUi(&authenticationDialog); + authenticationDialog.adjustSize(); + ui.siteDescription->setText(tr("A network proxy at %1 is requesting credentials for realm: %2") + .arg(proxy.hostName(), authenticator->realm())); + + // If the user passed credentials in the URL to http_proxy or similar they may be available to + // us. Otherwise this will just leave the fields empty + ui.userEdit->setText(proxy.user()); + ui.passwordEdit->setText(proxy.password()); + + if (authenticationDialog.exec() == QDialog::Accepted) { + authenticator->setUser(ui.userEdit->text()); + authenticator->setPassword(ui.passwordEdit->text()); + } +} +#endif diff --git a/examples/network/http/httpwindow.h b/examples/network/http/httpwindow.h index 64e9274288..ade0635e48 100644 --- a/examples/network/http/httpwindow.h +++ b/examples/network/http/httpwindow.h @@ -19,6 +19,9 @@ class QSslError; class QAuthenticator; class QNetworkReply; class QCheckBox; +#if QT_CONFIG(networkproxy) +class QNetworkProxy; +#endif QT_END_NAMESPACE @@ -52,6 +55,9 @@ private slots: #if QT_CONFIG(ssl) void sslErrors(const QList &errors); #endif +#if QT_CONFIG(networkproxy) + void slotProxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator); +#endif private: std::unique_ptr openFileForWrite(const QString &fileName);