7

How do I read the data from a QNetworkReply response from a specific URL before QWebPage does? but when the finished() signal is emited the reply is read already by QWebPage, so connect readyRead() or call reply->readAll() return nothing. I tried overload acceptNavigationRequest() method in my own QWebPage class, something like this:

bool webPage::acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, QWebPage::NavigationType type)
{
    //qDebug() << "filename = " << request.rawHeader("content-disposition");

    if(request.url().path() == QStringLiteral("download.php"))
    {
        QNetworkReply *reply = networkAccessManager()->get(request);
        QFile file;
        file.setFileName(filename);
        if(!file.open(QIODevice::ReadWrite))
        {
            /* handle error */
        }
        file.write(reply->readAll());
        file.close();
        return false;
    }

But I couldn't manage to reply work... the returned reply is invalid (don't even return a http status code, I know it means the http request sent is invalid but i don't know why).

Different approachs to solve this are welcome!

Jack
  • 16,276
  • 55
  • 159
  • 284
  • @MrEricSir fixed – Jack Aug 24 '17 at 03:26
  • try with this answer: https://stackoverflow.com/questions/5486090/qnetworkreply-wait-for-finished – eyllanesc Aug 24 '17 at 03:37
  • The answer from QNetworkReply is not automatic so you must connect the finished signal to a slot, and in that slot save the file or use an eventloop as shown by the response of the link that I have passed before. – eyllanesc Aug 24 '17 at 03:39

1 Answers1

7

Using the finished slot with a lambda expression, you can do this: -

QNetworkReply* reply = networkAccessManager()->get(request);

connect(reply, &QNetworkReply::finished, [=]() {

    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray response = reply->readAll();
        // do something with the data...
    }
    else // handle error
    {
      qDebug(pReply->errorString());
    }
});
TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85