23 #include <QNetworkReply> 28 if ( mReply && mReply->isRunning() )
35 mReply->deleteLater();
46 mContentLoaded =
false;
53 mReply->deleteLater();
58 mReply->setParent(
nullptr );
59 connect( mReply, &QNetworkReply::finished,
this, [ = ] { contentLoaded(); } );
65 if ( !mContentLoaded )
75 if ( !mContentLoaded || !mReply )
80 QByteArray array = mReply->readAll();
83 QTextCodec *codec = codecForHtml( array );
84 return codec->toUnicode( array );
95 mReply->deleteLater();
100 QTextCodec *QgsNetworkContentFetcher::codecForHtml( QByteArray &array )
const 107 QTextCodec *codec = QTextCodec::codecForUtfText( array,
nullptr );
114 QByteArray header = array.left( 1024 ).toLower();
115 int pos = header.indexOf(
"meta charset=" );
118 pos += int( strlen(
"meta charset=" ) ) + 1;
119 int pos2 = header.indexOf(
'\"', pos );
120 QByteArray cs = header.mid( pos, pos2 - pos );
121 codec = QTextCodec::codecForName( cs );
129 codec = QTextCodec::codecForHtml( array, codec );
136 return QTextCodec::codecForName(
"UTF-8" );
139 void QgsNetworkContentFetcher::contentLoaded(
bool ok )
149 if ( mReply->error() != QNetworkReply::NoError )
151 QgsMessageLog::logMessage( tr(
"HTTP fetch %1 failed with error %2" ).arg( mReply->url().toString(), mReply->errorString() ) );
152 mContentLoaded =
true;
157 QVariant redirect = mReply->attribute( QNetworkRequest::RedirectionTargetAttribute );
158 if ( redirect.isNull() )
161 QVariant status = mReply->attribute( QNetworkRequest::HttpStatusCodeAttribute );
162 if ( !status.isNull() && status.toInt() >= 400 )
164 QgsMessageLog::logMessage( tr(
"HTTP fetch %1 failed with error %2" ).arg( mReply->url().toString(), status.toString() ) );
166 mContentLoaded =
true;
172 mReply->deleteLater();
QString contentAsString() const
Returns the fetched content as a string.
void downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
Emitted when data is received.
QNetworkReply * reply()
Returns a reference to the network reply.
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.