I am trying to communicate with an external server to see if the user of the program has a license, so I must send a json to my server with the machine id to see the payment status of the account, then I should return a json content the information like number of days of the license, if it is paid etc.
QNetworkAccessManager am;
QNetworkRequest request(QUrl("http://localhost/ives/webserver/serverrequest.php"));
request.setHeader(QNetworkRequest::UserAgentHeader, "IVarejo");
QJsonObject root;
root.insert("tipoRequest", QJsonValue::fromVariant("validacao"));
QJsonDocument sendDoc;
sendDoc.setObject(root);
QString json = sendDoc.toJson(QJsonDocument::Compact);
qDebug() << "JSON: " << json;
QNetworkReply *reply = am.post(request, json.toUtf8());
qDebug() << "Resultado: " << reply->readAll();
php script:
<?php
if(isset($_POST))
echo json_encode($_POST);
?>
But I get an empty answer, unlike the browser when I send any data via form
JSON: "{\"tipoRequest\":\"validacao\"}"
Resultado: ""
After QNetworkReply *reply = am.post(request, json.toUtf8());
call You must wait for the response.
You can do it in two ways:
reply->waitForReadyRead();
qDebug() << "Resultado: " << reply->readAll(); //now You can use readAll
or connect to readyRead signal - preffered way in Qt, because it won't block your current thread.
connect(reply, &QIODevice::readyRead, [reply](){
qDebug() << "Resultado: " << reply->readAll();
});
Using lambdas is very convenient here, but it's not neccesary. You can connect it to a slot as well.
Also remember that:
Note: After the request has finished, it is the responsibility of the user to delete the QNetworkReply object at an appropriate time. Do not directly delete it inside the slot connected to finished(). You can use the deleteLater() function.