23#include "moc_qgsnetworkaccessmanager.cpp"
41#include <QNetworkReply>
42#include <QRecursiveMutex>
43#include <QThreadStorage>
44#include <QAuthenticator>
45#include <QStandardPaths>
51#include <QSslConfiguration>
59static std::vector< std::pair< QString, std::function< void( QNetworkRequest * ) > > > sCustomPreprocessors;
60static std::vector< std::pair< QString, std::function< void( QNetworkRequest *,
int &op, QByteArray *data ) > > > sCustomAdvancedPreprocessors;
61static std::vector< std::pair< QString, std::function< void(
const QNetworkRequest &, QNetworkReply * ) > > > sCustomReplyPreprocessors;
64class QgsNetworkProxyFactory :
public QNetworkProxyFactory
67 QgsNetworkProxyFactory() =
default;
69 QList<QNetworkProxy> queryProxy(
const QNetworkProxyQuery &query = QNetworkProxyQuery() )
override
75 for ( QNetworkProxyFactory *f : constProxyFactories )
77 QList<QNetworkProxy> systemproxies = QNetworkProxyFactory::systemProxyForQuery( query );
78 if ( !systemproxies.isEmpty() )
81 QList<QNetworkProxy> proxies = f->queryProxy( query );
82 if ( !proxies.isEmpty() )
87 if ( query.queryType() != QNetworkProxyQuery::UrlRequest )
90 const QString url = query.url().toString();
93 for (
const QString &noProxy : constNoProxyList )
95 if ( !noProxy.trimmed().isEmpty() && url.startsWith( noProxy ) )
97 QgsDebugMsgLevel( QStringLiteral(
"don't using any proxy for %1 [exclude %2]" ).arg( url, noProxy ), 4 );
98 return QList<QNetworkProxy>() << QNetworkProxy( QNetworkProxy::NoProxy );
103 for (
const QString &exclude : constExcludeList )
105 if ( !exclude.trimmed().isEmpty() && url.startsWith( exclude ) )
107 QgsDebugMsgLevel( QStringLiteral(
"using default proxy for %1 [exclude %2]" ).arg( url, exclude ), 4 );
108 return QList<QNetworkProxy>() << QNetworkProxy( QNetworkProxy::DefaultProxy );
114 QgsDebugMsgLevel( QStringLiteral(
"requesting system proxy for query %1" ).arg( url ), 4 );
115 QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery( query );
116 if ( !proxies.isEmpty() )
119 .arg( proxies.first().hostName() ).arg( proxies.first().port() ), 4 );
124 QgsDebugMsgLevel( QStringLiteral(
"using fallback proxy for %1" ).arg( url ), 4 );
131class QgsNetworkCookieJar :
public QNetworkCookieJar
137 : QNetworkCookieJar( parent )
141 bool deleteCookie(
const QNetworkCookie &cookie )
override
143 const QMutexLocker locker( &mMutex );
144 if ( QNetworkCookieJar::deleteCookie( cookie ) )
146 emit mNam->cookiesChanged( allCookies() );
151 bool insertCookie(
const QNetworkCookie &cookie )
override
153 const QMutexLocker locker( &mMutex );
154 if ( QNetworkCookieJar::insertCookie( cookie ) )
156 emit mNam->cookiesChanged( allCookies() );
161 bool setCookiesFromUrl(
const QList<QNetworkCookie> &cookieList,
const QUrl &url )
override
163 const QMutexLocker locker( &mMutex );
164 return QNetworkCookieJar::setCookiesFromUrl( cookieList, url );
166 bool updateCookie(
const QNetworkCookie &cookie )
override
168 const QMutexLocker locker( &mMutex );
169 if ( QNetworkCookieJar::updateCookie( cookie ) )
171 emit mNam->cookiesChanged( allCookies() );
178 QList<QNetworkCookie> allCookies()
const
180 const QMutexLocker locker( &mMutex );
181 return QNetworkCookieJar::allCookies();
183 void setAllCookies(
const QList<QNetworkCookie> &cookieList )
185 const QMutexLocker locker( &mMutex );
186 QNetworkCookieJar::setAllCookies( cookieList );
190 mutable QRecursiveMutex mMutex;
200 static QThreadStorage<QgsNetworkAccessManager> sInstances;
203 if ( nam->thread() == qApp->thread() )
206 if ( !nam->mInitialized )
216 : QNetworkAccessManager( parent )
217 , mSslErrorHandlerSemaphore( 1 )
218 , mAuthRequestHandlerSemaphore( 1 )
220 setRedirectPolicy( QNetworkRequest::NoLessSafeRedirectPolicy );
221 setProxyFactory(
new QgsNetworkProxyFactory() );
222 setCookieJar(
new QgsNetworkCookieJar(
this ) );
223 enableStrictTransportSecurityStore(
true );
224 setStrictTransportSecurityEnabled(
true );
229 Q_ASSERT( sMainNAM ==
this );
230 mSslErrorHandler = std::move( handler );
235 Q_ASSERT( sMainNAM ==
this );
236 mAuthHandler = std::move( handler );
241 mProxyFactories.insert( 0, factory );
246 mProxyFactories.removeAll( factory );
251 return mProxyFactories;
256 return mExcludedURLs;
266 return mFallbackProxy;
271 QgsDebugMsgLevel( QStringLiteral(
"proxy settings: (type:%1 host: %2:%3, user:%4, password:%5" )
272 .arg( proxy.type() == QNetworkProxy::DefaultProxy ? QStringLiteral(
"DefaultProxy" ) :
273 proxy.type() == QNetworkProxy::Socks5Proxy ? QStringLiteral(
"Socks5Proxy" ) :
274 proxy.type() == QNetworkProxy::NoProxy ? QStringLiteral(
"NoProxy" ) :
275 proxy.type() == QNetworkProxy::HttpProxy ? QStringLiteral(
"HttpProxy" ) :
276 proxy.type() == QNetworkProxy::HttpCachingProxy ? QStringLiteral(
"HttpCachingProxy" ) :
277 proxy.type() == QNetworkProxy::FtpCachingProxy ? QStringLiteral(
"FtpCachingProxy" ) :
278 QStringLiteral(
"Undefined" ),
282 proxy.password().isEmpty() ? QStringLiteral(
"not set" ) : QStringLiteral(
"set" ) ), 4 );
284 mFallbackProxy = proxy;
285 mExcludedURLs = excludes;
287 mExcludedURLs.erase( std::remove_if( mExcludedURLs.begin(), mExcludedURLs.end(),
288 [](
const QString & url )
290 return url.trimmed().isEmpty();
291 } ), mExcludedURLs.end() );
293 mNoProxyURLs = noProxyURLs;
294 mNoProxyURLs.erase( std::remove_if( mNoProxyURLs.begin(), mNoProxyURLs.end(),
295 [](
const QString & url )
297 return url.trimmed().isEmpty();
298 } ), mNoProxyURLs.end() );
305 QNetworkRequest *pReq(
const_cast< QNetworkRequest *
>( &req ) );
307 QString userAgent = s.
value( QStringLiteral(
"/qgis/networkAndProxy/userAgent" ),
"Mozilla/5.0" ).toString();
308 if ( !userAgent.isEmpty() )
310 userAgent += QStringLiteral(
"QGIS/%1/%2" ).arg(
Qgis::versionInt() ).arg( QSysInfo::prettyProductName() );
311 pReq->setRawHeader(
"User-Agent", userAgent.toLatin1() );
314 const bool ishttps = pReq->url().scheme().compare( QLatin1String(
"https" ), Qt::CaseInsensitive ) == 0;
317 QgsDebugMsgLevel( QStringLiteral(
"Adding trusted CA certs to request" ), 3 );
318 QSslConfiguration sslconfig( pReq->sslConfiguration() );
322 const QString hostport( QStringLiteral(
"%1:%2" )
323 .arg( pReq->url().host().trimmed() )
324 .arg( pReq->url().port() != -1 ? pReq->url().port() : 443 ) );
326 if ( !servconfig.
isNull() )
328 QgsDebugMsgLevel( QStringLiteral(
"Adding SSL custom config to request for %1" ).arg( hostport ), 2 );
334 pReq->setSslConfiguration( sslconfig );
338 if ( sMainNAM->mCacheDisabled )
341 pReq->setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork );
342 pReq->setAttribute( QNetworkRequest::CacheSaveControlAttribute,
false );
345 for (
const auto &preprocessor : sCustomPreprocessors )
347 preprocessor.second( pReq );
350 static QAtomicInt sRequestId = 0;
351 const int requestId = ++sRequestId;
353 if ( QBuffer *buffer = qobject_cast<QBuffer *>( outgoingData ) )
355 content = buffer->buffer();
358 for (
const auto &preprocessor : sCustomAdvancedPreprocessors )
360 int intOp =
static_cast< int >( op );
361 preprocessor.second( pReq, intOp, &content );
362 op =
static_cast< QNetworkAccessManager::Operation
>( intOp );
369 QNetworkReply *reply = QNetworkAccessManager::createRequest( op, req, outgoingData );
370 reply->setProperty(
"requestId", requestId );
377 connect( reply, &QNetworkReply::downloadProgress,
this, &QgsNetworkAccessManager::onReplyDownloadProgress );
379 connect( reply, &QNetworkReply::sslErrors,
this, &QgsNetworkAccessManager::onReplySslErrors );
382 for (
const auto &replyPreprocessor : sCustomReplyPreprocessors )
384 replyPreprocessor.second( req, reply );
392 QTimer *timer =
new QTimer( reply );
393 timer->setObjectName( QStringLiteral(
"timeoutTimer" ) );
394 connect( timer, &QTimer::timeout,
this, &QgsNetworkAccessManager::abortRequest );
395 timer->setSingleShot(
true );
398 connect( reply, &QNetworkReply::downloadProgress, timer, [timer] { timer->start(); } );
399 connect( reply, &QNetworkReply::uploadProgress, timer, [timer] { timer->start(); } );
400 connect( reply, &QNetworkReply::finished, timer, &QTimer::stop );
402 QgsDebugMsgLevel( QStringLiteral(
"Created [reply:%1]" ).arg(
reinterpret_cast< qint64
>( reply ), 0, 16 ), 3 );
407void QgsNetworkAccessManager::abortRequest()
409 QTimer *timer = qobject_cast<QTimer *>( sender() );
412 QNetworkReply *reply = qobject_cast<QNetworkReply *>( timer->parent() );
416 QgsDebugMsgLevel( QStringLiteral(
"Abort [reply:%1] %2" ).arg(
reinterpret_cast< qint64
>( reply ), 0, 16 ).arg( reply->url().toString() ), 3 );
423void QgsNetworkAccessManager::onReplyFinished( QNetworkReply *reply )
428void QgsNetworkAccessManager::onReplyDownloadProgress( qint64 bytesReceived, qint64 bytesTotal )
430 if ( QNetworkReply *reply = qobject_cast< QNetworkReply *>( sender() ) )
437void QgsNetworkAccessManager::onReplySslErrors(
const QList<QSslError> &errors )
439 QNetworkReply *reply = qobject_cast< QNetworkReply *>( sender() );
441 Q_ASSERT( reply->manager() ==
this );
443 QgsDebugMsgLevel( QStringLiteral(
"Stopping network reply timeout whilst SSL error is handled" ), 2 );
444 pauseTimeout( reply );
449 mSslErrorHandlerSemaphore.acquire();
453 emit sslErrorsOccurred( reply, errors );
454 if (
this != sMainNAM )
458 mSslErrorHandlerSemaphore.acquire();
459 mSslErrorHandlerSemaphore.release();
460 afterSslErrorHandled( reply );
464void QgsNetworkAccessManager::afterSslErrorHandled( QNetworkReply *reply )
466 if ( reply->manager() ==
this )
468 restartTimeout( reply );
469 emit sslErrorsHandled( reply );
473void QgsNetworkAccessManager::afterAuthRequestHandled( QNetworkReply *reply )
475 if ( reply->manager() ==
this )
477 restartTimeout( reply );
478 emit authRequestHandled( reply );
482void QgsNetworkAccessManager::pauseTimeout( QNetworkReply *reply )
484 Q_ASSERT( reply->manager() ==
this );
486 QTimer *timer = reply->findChild<QTimer *>( QStringLiteral(
"timeoutTimer" ) );
487 if ( timer && timer->isActive() )
493void QgsNetworkAccessManager::restartTimeout( QNetworkReply *reply )
495 Q_ASSERT( reply->manager() ==
this );
497 QTimer *timer = reply->findChild<QTimer *>( QStringLiteral(
"timeoutTimer" ) );
500 Q_ASSERT( !timer->isActive() );
501 QgsDebugMsgLevel( QStringLiteral(
"Restarting network reply timeout" ), 2 );
502 timer->setSingleShot(
true );
507int QgsNetworkAccessManager::getRequestId( QNetworkReply *reply )
509 return reply->property(
"requestId" ).toInt();
512void QgsNetworkAccessManager::handleSslErrors( QNetworkReply *reply,
const QList<QSslError> &errors )
514 mSslErrorHandler->handleSslErrors( reply, errors );
515 afterSslErrorHandled( reply );
516 qobject_cast<QgsNetworkAccessManager *>( reply->manager() )->mSslErrorHandlerSemaphore.release();
521void QgsNetworkAccessManager::onAuthRequired( QNetworkReply *reply, QAuthenticator *auth )
524 Q_ASSERT( reply->manager() ==
this );
526 QgsDebugMsgLevel( QStringLiteral(
"Stopping network reply timeout whilst auth request is handled" ), 2 );
527 pauseTimeout( reply );
532 mAuthRequestHandlerSemaphore.acquire();
536 emit authRequestOccurred( reply, auth );
538 if (
this != sMainNAM )
542 mAuthRequestHandlerSemaphore.acquire();
543 mAuthRequestHandlerSemaphore.release();
544 afterAuthRequestHandled( reply );
550 if (
this != sMainNAM )
556 mAuthHandler->handleAuthRequestOpenBrowser( url );
561 if (
this != sMainNAM )
567 mAuthHandler->handleAuthRequestCloseBrowser();
572 if (
this != sMainNAM )
579void QgsNetworkAccessManager::handleAuthRequest( QNetworkReply *reply, QAuthenticator *auth )
581 mAuthHandler->handleAuthRequest( reply, auth );
585 afterAuthRequestHandled( reply );
586 qobject_cast<QgsNetworkAccessManager *>( reply->manager() )->mAuthRequestHandlerSemaphore.release();
593 case QNetworkRequest::AlwaysNetwork:
594 return QStringLiteral(
"AlwaysNetwork" );
595 case QNetworkRequest::PreferNetwork:
596 return QStringLiteral(
"PreferNetwork" );
597 case QNetworkRequest::PreferCache:
598 return QStringLiteral(
"PreferCache" );
599 case QNetworkRequest::AlwaysCache:
600 return QStringLiteral(
"AlwaysCache" );
602 return QStringLiteral(
"PreferNetwork" );
607 if ( name == QLatin1String(
"AlwaysNetwork" ) )
609 return QNetworkRequest::AlwaysNetwork;
611 else if ( name == QLatin1String(
"PreferNetwork" ) )
613 return QNetworkRequest::PreferNetwork;
615 else if ( name == QLatin1String(
"PreferCache" ) )
617 return QNetworkRequest::PreferCache;
619 else if ( name == QLatin1String(
"AlwaysCache" ) )
621 return QNetworkRequest::AlwaysCache;
623 return QNetworkRequest::PreferNetwork;
629 mUseSystemProxy =
false;
631 Q_ASSERT( sMainNAM );
633 if ( sMainNAM !=
this )
635 connect(
this, &QNetworkAccessManager::proxyAuthenticationRequired,
636 sMainNAM, &QNetworkAccessManager::proxyAuthenticationRequired,
657 connect(
this, &QNetworkAccessManager::sslErrors,
658 sMainNAM, &QNetworkAccessManager::sslErrors,
671 if ( !mSslErrorHandler )
675 setAuthHandler( std::make_unique< QgsNetworkAuthenticationHandler>() );
678 connect(
this, &QgsNetworkAccessManager::sslErrorsOccurred, sMainNAM, &QgsNetworkAccessManager::handleSslErrors );
680 connect(
this, &QNetworkAccessManager::authenticationRequired,
this, &QgsNetworkAccessManager::onAuthRequired );
681 connect(
this, &QgsNetworkAccessManager::authRequestOccurred, sMainNAM, &QgsNetworkAccessManager::handleAuthRequest );
683 connect(
this, &QNetworkAccessManager::finished,
this, &QgsNetworkAccessManager::onReplyFinished );
688 QStringList excludes;
689 QStringList noProxyURLs;
691 const bool proxyEnabled = settings.
value( QStringLiteral(
"proxy/proxyEnabled" ),
false ).toBool();
696 excludes = settings.
value( QStringLiteral(
"proxy/proxyExcludedUrls" ), QStringList() ).toStringList();
698 noProxyURLs = settings.
value( QStringLiteral(
"proxy/noProxyUrls" ), QStringList() ).toStringList();
701 const QString proxyHost = settings.
value( QStringLiteral(
"proxy/proxyHost" ),
"" ).toString();
702 const int proxyPort = settings.
value( QStringLiteral(
"proxy/proxyPort" ),
"" ).toString().toInt();
704 const QString proxyUser = settings.
value( QStringLiteral(
"proxy/proxyUser" ),
"" ).toString();
705 const QString proxyPassword = settings.
value( QStringLiteral(
"proxy/proxyPassword" ),
"" ).toString();
707 const QString proxyTypeString = settings.
value( QStringLiteral(
"proxy/proxyType" ),
"" ).toString();
709 if ( proxyTypeString == QLatin1String(
"DefaultProxy" ) )
711 mUseSystemProxy =
true;
712 QNetworkProxyFactory::setUseSystemConfiguration(
true );
713 QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery();
714 if ( !proxies.isEmpty() )
716 proxy = proxies.first();
722 QNetworkProxy::ProxyType proxyType = QNetworkProxy::DefaultProxy;
723 if ( proxyTypeString == QLatin1String(
"Socks5Proxy" ) )
725 proxyType = QNetworkProxy::Socks5Proxy;
727 else if ( proxyTypeString == QLatin1String(
"HttpProxy" ) )
729 proxyType = QNetworkProxy::HttpProxy;
731 else if ( proxyTypeString == QLatin1String(
"HttpCachingProxy" ) )
733 proxyType = QNetworkProxy::HttpCachingProxy;
735 else if ( proxyTypeString == QLatin1String(
"FtpCachingProxy" ) )
737 proxyType = QNetworkProxy::FtpCachingProxy;
741 .arg( proxyHost ).arg( proxyPort )
742 .arg( proxyUser, proxyPassword ), 2
744 proxy = QNetworkProxy( proxyType, proxyHost, proxyPort, proxyUser, proxyPassword );
747 const QString authcfg = settings.
value( QStringLiteral(
"proxy/authcfg" ),
"" ).toString();
748 if ( !authcfg.isEmpty( ) )
750 QgsDebugMsgLevel( QStringLiteral(
"setting proxy from stored authentication configuration %1" ).arg( authcfg ), 2 );
753 authManager->updateNetworkProxy( proxy, authcfg );
764 if ( cacheDirectory.isEmpty() )
765 cacheDirectory = QStandardPaths::writableLocation( QStandardPaths::CacheLocation );
773 if ( cache() != newcache )
774 setCache( newcache );
776 if (
this != sMainNAM )
778 static_cast<QgsNetworkCookieJar *
>( cookieJar() )->setAllCookies(
static_cast<QgsNetworkCookieJar *
>( sMainNAM->cookieJar() )->allCookies() );
782void QgsNetworkAccessManager::syncCookies(
const QList<QNetworkCookie> &cookies )
784 if ( sender() !=
this )
786 static_cast<QgsNetworkCookieJar *
>( cookieJar() )->setAllCookies( cookies );
787 if (
this == sMainNAM )
808 br.
get( request, forceRefresh, feedback );
816 br.
post( request, data, forceRefresh, feedback );
822 QString
id = QUuid::createUuid().toString();
823 sCustomPreprocessors.emplace_back( std::make_pair(
id, processor ) );
829 const size_t prevCount = sCustomPreprocessors.size();
830 sCustomPreprocessors.erase( std::remove_if( sCustomPreprocessors.begin(), sCustomPreprocessors.end(), [
id]( std::pair< QString, std::function<
void( QNetworkRequest * ) > > &a )
832 return a.first == id;
833 } ), sCustomPreprocessors.end() );
834 return prevCount != sCustomPreprocessors.size();
839 const size_t prevCount = sCustomAdvancedPreprocessors.size();
840 sCustomAdvancedPreprocessors.erase( std::remove_if( sCustomAdvancedPreprocessors.begin(), sCustomAdvancedPreprocessors.end(), [
id]( std::pair< QString, std::function<
void( QNetworkRequest *,
int &, QByteArray * ) > > &a )
842 return a.first == id;
843 } ), sCustomAdvancedPreprocessors.end() );
844 return prevCount != sCustomAdvancedPreprocessors.size();
849 QString
id = QUuid::createUuid().toString();
850 sCustomAdvancedPreprocessors.emplace_back( std::make_pair(
id, processor ) );
856 QString
id = QUuid::createUuid().toString();
857 sCustomReplyPreprocessors.emplace_back( std::make_pair(
id, processor ) );
863 const size_t prevCount = sCustomReplyPreprocessors.size();
864 sCustomReplyPreprocessors.erase( std::remove_if( sCustomReplyPreprocessors.begin(), sCustomReplyPreprocessors.end(), [
id]( std::pair< QString, std::function<
void(
const QNetworkRequest &, QNetworkReply * ) > > &a )
866 return a.first == id;
867 } ), sCustomReplyPreprocessors.end() );
868 return prevCount != sCustomReplyPreprocessors.size();
873 for (
const auto &preprocessor : sCustomPreprocessors )
875 preprocessor.second( req );
885 : mOperation( operation )
886 , mRequest( request )
887 , mOriginatingThreadId( QStringLiteral(
"0x%2" ).arg( reinterpret_cast<quintptr>( QThread::currentThread() ), 2 * QT_POINTER_SIZE, 16, QLatin1Char(
'0' ) ) )
888 , mRequestId( requestId )
889 , mContent( content )
890 , mInitiatorClass( request.attribute( static_cast< QNetworkRequest::Attribute >(
QgsNetworkRequestParameters::AttributeInitiatorClass ) ).toString() )
891 , mInitiatorRequestId( request.attribute( static_cast< QNetworkRequest::Attribute >(
QgsNetworkRequestParameters::AttributeInitiatorRequestId ) ) )
903 QgsDebugError( QStringLiteral(
"SSL errors occurred accessing URL:\n%1" ).arg( reply->request().url().toString() ) );
913 QgsDebugError( QStringLiteral(
"Network reply required authentication, but no handler was in place to provide this authentication request while accessing the URL:\n%1" ).arg( reply->request().url().toString() ) );
919 QgsDebugError( QStringLiteral(
"Network authentication required external browser to open URL %1, but no handler was in place" ).arg( url.toString() ) );
924 QgsDebugError( QStringLiteral(
"Network authentication required external browser closed, but no handler was in place" ) );
928#include "qgsnetworkaccessmanager.moc"
static int versionInt()
Version number used for comparing versions using the "Check QGIS Version" function.
static QgsAuthManager * authManager()
Returns the application's authentication manager instance.
static QList< QSslCertificate > casMerge(const QList< QSslCertificate > &bundle1, const QList< QSslCertificate > &bundle2)
casMerge merges two certificate bundles in a single one removing duplicates, the certificates from th...
Configuration container for SSL server connection exceptions or overrides.
QSsl::SslProtocol sslProtocol() const
SSL server protocol to use in connections.
int sslPeerVerifyDepth() const
Number or SSL client's peer to verify in connections.
bool isNull() const
Whether configuration is null (missing components)
QSslSocket::PeerVerifyMode sslPeerVerifyMode() const
SSL client's peer verify mode to use in connections.
Singleton offering an interface to manage the authentication configuration database and to utilize co...
const QgsAuthConfigSslServer sslCertCustomConfigByHost(const QString &hostport)
sslCertCustomConfigByHost get an SSL certificate custom config by hostport (host:port)
A thread safe class for performing blocking (sync) network requests, with full support for QGIS proxy...
ErrorCode post(QNetworkRequest &request, QIODevice *data, bool forceRefresh=false, QgsFeedback *feedback=nullptr)
Performs a "post" operation on the specified request, using the given data.
void setAuthCfg(const QString &authCfg)
Sets the authentication config id which should be used during the request.
ErrorCode get(QNetworkRequest &request, bool forceRefresh=false, QgsFeedback *feedback=nullptr, RequestFlags requestFlags=QgsBlockingNetworkRequest::RequestFlags())
Performs a "get" operation on the specified request.
QgsNetworkReplyContent reply() const
Returns the content of the network reply, after a get(), post(), head() or put() request has been mad...
Base class for feedback objects to be used for cancellation of something running in a worker thread.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE())
Adds a message to the log instance (and creates it if necessary).
network access manager for QGIS
QStringList noProxyList() const
Returns the no proxy list.
void finished(QgsNetworkReplyContent reply)
Emitted whenever a pending network reply is finished.
static const QgsSettingsEntryInteger * settingsNetworkTimeout
Settings entry network timeout.
void cookiesChanged(const QList< QNetworkCookie > &cookies)
Emitted when the cookies changed.
static QgsNetworkReplyContent blockingGet(QNetworkRequest &request, const QString &authCfg=QString(), bool forceRefresh=false, QgsFeedback *feedback=nullptr)
Posts a GET request to obtain the contents of the target request and returns a new QgsNetworkReplyCon...
void insertProxyFactory(QNetworkProxyFactory *factory)
Inserts a factory into the proxy factories list.
void setSslErrorHandler(std::unique_ptr< QgsSslErrorHandler > handler)
Sets the application SSL error handler, which is used to respond to SSL errors encountered during net...
Q_DECL_DEPRECATED void requestAboutToBeCreated(QNetworkAccessManager::Operation operation, const QNetworkRequest &request, QIODevice *device)
void abortAuthBrowser()
Abort any outstanding external browser login request.
void setCacheDisabled(bool disabled)
Sets whether all network caching should be disabled.
const QList< QNetworkProxyFactory * > proxyFactories() const
Returns a list of proxy factories used by the manager.
void downloadProgress(int requestId, qint64 bytesReceived, qint64 bytesTotal)
Emitted when a network reply receives a progress report.
void requestAuthOpenBrowser(const QUrl &url) const
Forwards an external browser login url opening request to the authentication handler.
void requestAuthCloseBrowser() const
Forwards an external browser login closure request to the authentication handler.
void requestEncounteredSslErrors(int requestId, const QList< QSslError > &errors)
Emitted when a network request encounters SSL errors.
static QString cacheLoadControlName(QNetworkRequest::CacheLoadControl control)
Returns the name for QNetworkRequest::CacheLoadControl.
void requestCreated(const QgsNetworkRequestParameters &request)
Emitted when a network request has been created.
static QString setReplyPreprocessor(const std::function< void(const QNetworkRequest &, QNetworkReply *)> &processor)
Sets a reply pre-processor function, which allows manipulation of QNetworkReply objects after they ar...
static bool removeRequestPreprocessor(const QString &id)
Removes the custom request pre-processor function with matching id.
void requestAuthDetailsAdded(int requestId, const QString &realm, const QString &user, const QString &password)
Emitted when network authentication details have been added to a request.
static QNetworkRequest::CacheLoadControl cacheLoadControlFromName(const QString &name)
Returns QNetworkRequest::CacheLoadControl from a name.
bool cacheDisabled() const
Returns true if all network caching is disabled.
static bool removeAdvancedRequestPreprocessor(const QString &id)
Removes an advanced request pre-processor function with matching id.
QgsNetworkAccessManager(QObject *parent=nullptr)
void requestRequiresAuth(int requestId, const QString &realm)
Emitted when a network request prompts an authentication request.
void preprocessRequest(QNetworkRequest *req) const
Preprocesses request.
void setAuthHandler(std::unique_ptr< QgsNetworkAuthenticationHandler > handler)
Sets the application network authentication handler, which is used to respond to network authenticati...
static void setTimeout(int time)
Sets the maximum timeout time for network requests, in milliseconds.
static QString setAdvancedRequestPreprocessor(const std::function< void(QNetworkRequest *, int &op, QByteArray *data)> &processor)
Sets an advanced request pre-processor function, which allows manipulation of a network request befor...
static QgsNetworkReplyContent blockingPost(QNetworkRequest &request, const QByteArray &data, const QString &authCfg=QString(), bool forceRefresh=false, QgsFeedback *feedback=nullptr)
Posts a POST request to obtain the contents of the target request, using the given data,...
const QNetworkProxy & fallbackProxy() const
Returns the fallback proxy used by the manager.
static int timeout()
Returns the network timeout length, in milliseconds.
void setupDefaultProxyAndCache(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Setup the QgsNetworkAccessManager (NAM) according to the user's settings.
static QString setRequestPreprocessor(const std::function< void(QNetworkRequest *request)> &processor)
Sets a request pre-processor function, which allows manipulation of a network request before it is pr...
void setFallbackProxyAndExcludes(const QNetworkProxy &proxy, const QStringList &excludes, const QStringList &noProxyURLs)
Sets the fallback proxy and URLs which shouldn't use it.
static bool removeReplyPreprocessor(const QString &id)
Removes the custom reply pre-processor function with matching id.
QStringList excludeList() const
Returns the proxy exclude list.
static QgsNetworkAccessManager * instance(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Returns a pointer to the active QgsNetworkAccessManager for the current thread.
void removeProxyFactory(QNetworkProxyFactory *factory)
Removes a factory from the proxy factories list.
void authBrowserAborted()
Emitted when external browser logins are to be aborted.
void requestTimedOut(QgsNetworkRequestParameters request)
Emitted when a network request has timed out.
bool useSystemProxy() const
Returns whether the system proxy should be used.
QNetworkReply * createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &req, QIODevice *outgoingData=nullptr) override
virtual void handleAuthRequest(QNetworkReply *reply, QAuthenticator *auth)
Called whenever network authentication requests are encountered during a network reply.
virtual void handleAuthRequestCloseBrowser()
Called to terminate a network authentication through external browser.
virtual void handleAuthRequestOpenBrowser(const QUrl &url)
Called to initiate a network authentication through external browser url.
Wrapper implementation of QNetworkDiskCache with all methods guarded by a mutex soly for internal use...
void setCacheDirectory(const QString &cacheDir)
qint64 maximumCacheSize() const
void setMaximumCacheSize(qint64 size)
QString cacheDirectory() const
Encapsulates a network reply within a container which is inexpensive to copy and safe to pass between...
Encapsulates parameters and properties of a network request.
QgsNetworkRequestParameters()=default
T value(const QString &dynamicKeyPart=QString()) const
Returns settings value.
bool setValue(const T &value, const QString &dynamicKeyPart=QString()) const
Set settings value.
An integer settings entry.
static const QgsSettingsEntryInteger64 * settingsNetworkCacheSize
Settings entry network cache directory.
static const QgsSettingsEntryString * settingsNetworkCacheDirectory
Settings entry network cache directory.
static QgsSettingsTreeNode * sTreeNetwork
This class is a composition of two QSettings instances:
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
virtual void handleSslErrors(QNetworkReply *reply, const QList< QSslError > &errors)
Called whenever SSL errors are encountered during a network reply.
#define Q_NOWARN_DEPRECATED_POP
#define Q_NOWARN_DEPRECATED_PUSH
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)