I need to obtain some data from QNetworkReply to parse later, but every time the returned data is 0 when use qDebug() << getData().
I don’t want to save it in a file, then how to get the data from the QNetworkReply slot and store it in a string?
Please help! Thanks a lot.
#include <QByteArray>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
class Fetch : public QObject
{
Q_OBJECT
public:
Fetch(){};
void go(const QString &str, QUrl &url)
{
QNetworkRequest request;
request.setUrl(url);
QByteArray data = str.toUtf8();
QNetworkAccessManager* manager = new QNetworkAccessManager(this);
reply = manager->post(request, data);
connect(reply, SIGNAL(finished()), SLOT(httpFinished()));
}
QString getData()
{
return QString::fromUtf8(m_data);
}
private slots:
void httpFinished()
{
m_data = reply->readAll();
}
private:
QByteArray m_data;
QNetworkReply* reply;
};
if you doing something like that:
the problem is in asynchrony. When you call getData, there is no immediate reply from server.
You have to wait while request is processed and call this method after.
You have to use signals and slots