simple network request return empty string
-
Hi, i am trying to build a project which requests a data from website ,parse document, and store them in a table.
void MainWindow::on_pushButton_clicked() { QNetworkAccessManager *mana = new QNetworkAccessManager(this); QString url ="https://openapi.naver.com/v1/search/news.json?query="; QString keyword = ui->lineEdit->text(); url += keyword; QNetworkRequest req; req.setUrl (QUrl(url)); req.setRawHeader("X-Naver-Client-Id", id); req.setRawHeader("X-Naver-Client-Secret", pwd); QNetworkReply *reply = mana->get(req); qDebug() << reply->readAll(); }
Here is my code so far to check if anything came back.
googled a lot, saw similar codes to what i wrote but couldn't make it return anything other than empty string.
what am i doing wrong and how can i fix it? or any exemplary code for my purpose will be appreciated.
-
@sodu Qt is asynchronous so you must use the signals to get the result:
QNetworkAccessManager *mana = new QNetworkAccessManager(this); connect(mana, &QNetworkAccessManager::finished, this, &MainWindow::handleFinished);
void MainWindow::handleFinished(QNetworkReply *reply){ qDebug() << reply->readAll(); reply->deleteLater(); }
-
Another option is to block on QIODevice::waitForReadyRead, followed by read or readAll if true was returned.
The readyRead or finished signals are usually the better option, presuming there is an event loop running anyway. The documentation contains this curious note for the QAbstractSocket::waitForReadyRead override that is worth considering:
This function may fail randomly on Windows. Consider using the event loop and the readyRead() signal if your software will run on Windows. -
Another option is to block on QIODevice::waitForReadyRead
I'd suggest not to follow this way, please take a look at @eyllanesc mention working asynchronously with signals/slots...