How do I read the data from QNetworkReply?
Asked Answered
O

1

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!

Origen answered 24/8, 2017 at 3:6 Comment(3)
@MrEricSir fixedOrigen
try with this answer: #5486590Koblenz
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.Koblenz
E
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());
    }
});
Endosteum answered 24/8, 2017 at 8:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.