ty812
ty812

Reputation: 3323

Getting a page content with Qt

I am trying to get the content of a HTTP request into a QString variable with Qt and C++

QNetworkAccessManager networkManager;

QUrl url("https://someurl.test.com/this-actually-exists");
QNetworkRequest request;
request.setUrl(url);

QNetworkReply* currentReply = networkManager.get(request);  // GET

QString reply = QTextCodec::codecForMib(1015)->toUnicode(currentReply->readAll());

Still, the variable reply seems to stay empty. Obviously, I misunderstand the documentation. How do I get this to perform?

Upvotes: 2

Views: 1704

Answers (2)

Nejat
Nejat

Reputation: 32635

You can use two different ways even the synchronous or asynchronous ways to do this. The asynchronous way is :

connect (&networkManager , SIGNAL(finished(QNetworkReply*)) ,this, SLOT(done(QNetworkReply*)));

networkManager.get(request);

And you should read the contents from the returned reply in the slot connected to finished signal in the following way :

void net::done(QNetworkReply * reply) 
{
    if (reply->error() == QNetworkReply::NoError)
    {
       data = QString(reply->readAll ());
    }
    else
    {
       data = QString(reply->errorString ());
    }
}

The synchronous way is like :

   QNetworkReply *reply = networkManager.get(request);

   QEventLoop loop;
   connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
   connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), &loop, SLOT(quit()));
   loop.exec();

   QByteArray bts = reply->readAll();
   QString str(bts);

Here you use an event loop to wait until the reply is finished and then read the available bytes and get the string.

Upvotes: 3

St0fF
St0fF

Reputation: 1633

I need to assume you're running an application with an event-loop in place? If not, then it's a bit harder...

If so, replace your last line that builds the reply QString:

connect(currentReply, SIGNAL(finished()), this, SLOT(gotAReply()));

Then you'll have to define another method in your class as a slot that gets triggered as soon as that reply got filled:

void gotAReply()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());

    if (reply)
    {
        if (reply->error() == QNetworkReply::NoError)
        {
            QString replyText( reply->readAll() );
        }
        reply->deleteLater();
    }
}

Don't forget: for Signals and Slot to work your class declaration must contain the Q_OBJECT macro.

Upvotes: 1

Related Questions