c – 如何从QNetworkReply读取数据?

如何在QWebPage之前从特定URL读取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请求无效但我不知道为什么).

欢迎采用不同的方法来解决这个问题!

最佳答案 使用带有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());
    }
});
点赞