23 #include <QNetworkReply> 28 if ( mReply && mReply->isRunning() )
35 mReply->deleteLater();
46 mContentLoaded =
false;
53 mReply->deleteLater();
58 connect( mReply, &QNetworkReply::finished,
this, [ = ] { contentLoaded(); } );
64 if ( !mContentLoaded )
74 if ( !mContentLoaded || !mReply )
79 QByteArray array = mReply->readAll();
82 QTextCodec *codec = codecForHtml( array );
83 return codec->toUnicode( array );
94 mReply->deleteLater();
99 QTextCodec *QgsNetworkContentFetcher::codecForHtml( QByteArray &array )
const 106 QTextCodec *codec = QTextCodec::codecForUtfText( array,
nullptr );
113 QByteArray header = array.left( 1024 ).toLower();
114 int pos = header.indexOf(
"meta charset=" );
117 pos += int( strlen(
"meta charset=" ) ) + 1;
118 int pos2 = header.indexOf(
'\"', pos );
119 QByteArray cs = header.mid( pos, pos2 - pos );
120 codec = QTextCodec::codecForName( cs );
128 codec = QTextCodec::codecForHtml( array, codec );
135 return QTextCodec::codecForName(
"UTF-8" );
138 void QgsNetworkContentFetcher::contentLoaded(
bool ok )
148 if ( mReply->error() != QNetworkReply::NoError )
150 QgsMessageLog::logMessage( tr(
"HTTP fetch %1 failed with error %2" ).arg( mReply->url().toString(), mReply->errorString() ) );
151 mContentLoaded =
true;
156 QVariant redirect = mReply->attribute( QNetworkRequest::RedirectionTargetAttribute );
157 if ( redirect.isNull() )
160 QVariant status = mReply->attribute( QNetworkRequest::HttpStatusCodeAttribute );
161 if ( !status.isNull() && status.toInt() >= 400 )
163 QgsMessageLog::logMessage( tr(
"HTTP fetch %1 failed with error %2" ).arg( mReply->url().toString(), status.toString() ) );
165 mContentLoaded =
true;
171 mReply->deleteLater();
void downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
Emitted when data is received.
QNetworkReply * reply()
Returns a reference to the network reply.
QString contentAsString() const
Returns the fetched content as a string.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
void finished()
Emitted when content has loaded.
void cancel()
Cancels any ongoing request.
static QgsNetworkAccessManager * instance(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Returns a pointer to the active QgsNetworkAccessManager for the current thread.
~QgsNetworkContentFetcher() override
void fetchContent(const QUrl &url)
Fetches content from a remote URL and handles redirects.