如何从QNetworkReply读取数据?

时间:2017-08-24 03:06:40

标签: c++ qt windows-10 qt5 qnetworkreply

如何在QWebPage之前从特定网址的QNetworkReply响应中读取数据?但是当finished()信号被发出时,QWebPage已经读取了回复,因此连接readyRead()或调用reply->readAll()不会返回任何内容。我尝试在我自己的QWebPage类中重载acceptNavigationRequest()方法,如下所示:

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;
    }

但是我无法回复工作...返回的回复无效(甚至不返回http状态代码,我知道这意味着发送的http请求无效但我不知道为什么)。

欢迎不同的解决方法!

1 个答案:

答案 0 :(得分:1)

使用带有lambda表达式的成品槽,您可以这样做: -

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());
    }
});