Qt - Getting source ( HTML code ) of a web page hosted on the internet

Alaa Elrifaie picture Alaa Elrifaie · Jul 26, 2014 · Viewed 10.7k times · Source

I want to get the source (HTML) of a webpage, for example the homepage of StackOverflow.

This is what I've coded so far:

QNetworkAccessManager manager;
QNetworkReply *response = manager.get(QNetworkRequest(QUrl(url)));

QString html = response->readAll(); // Source should be stored here

But nothing happens! When I try to get the value of the html string it's empty ("").

So, what to do? I am using Qt 5.3.1.

Answer

Pavel Strakhov picture Pavel Strakhov · Jul 26, 2014

QNetworkAccessManager works asynchronously. You call readAll() immediately after get(), but the request has not been made in that moment. You need to use QNetworkAccessManager::finished signal as shown in the documentation and move readAll() to the slot connected to this signal.