duanliang2017 2019-07-30 14:48
浏览 172

如何将json发送到php脚本并使用Qt获得答案

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:  ""
  • 写回答

1条回答 默认 最新

  • doucong6884 2019-07-30 15:08
    关注

    After QNetworkReply *reply = am.post(request, json.toUtf8()); call You must wait for the response.

    You can do it in two ways:

    waitForReadyRead

    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.

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?