how can I read the data sent from the server in a variable of type QNetWorkReply?

坚强是说给别人听的谎言 提交于 2019-12-19 11:45:07

问题


I have used this code to sent the user name and a password to the server using POST Method. This returns me a reply,So how can I access the reply variable in the way that i can read the data sent from the server back to me ??

Used Code:

void MainWindow::post(QString name, QString password)
{
    QUrl serviceUrl = QUrl("http://lascivio.co/mobile/post.php");
    QByteArray postData;
    QString s = "param1="+name+"&";
    postData.append(s);
    s = "param2=" +password;
    postData.append(s);
    QNetworkAccessManager *networkManager = new QNetworkAccessManager(this);
    connect(networkManager, SIGNAL(finished(QNetworkReply*)), this,     SLOT(serviceRequestFinished(QNetworkReply*)));
    QNetworkRequest request;
    request.setUrl(serviceUrl);
    QNetworkReply* reply = networkManager->post(request, postData);
}
void MainWindow::serviceRequestFinished(QNetworkReply* reply)
{
//????????????
}

回答1:


QNetworkReply is a QIODevice, so you can read it the same way you would read a file. But you have to destroy the QNetworkReply and check for error too in that slot.

For example, in the simplest case (without HTTP redirection):

void MainWindow::serviceRequestFinished(QNetworkReply* reply)
{
    // At the end of that slot, we won't need it anymore
    reply->deleteLater();

    if(reply->error() == QNetworkReply::NoError) {
        QByteArray data = reply->readAll();
        // do something with data
        ...
    } else {
        // Handle the error
        ...
    }
}

You should probably declare the QNetworkAccessManager variable as a member of your class instead of creating a new one for each request.



来源:https://stackoverflow.com/questions/7177433/how-can-i-read-the-data-sent-from-the-server-in-a-variable-of-type-qnetworkreply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!