我想做一个简单的帖子请求int main.cpp。看来,当我运行该应用程序时,它不会执行代码,只会跳过它。
我尝试使用qt调试器,但是调试器启动后,下面的代码恰好在此之后结束。
我已经用邮递员测试了我的api,并且知道它可以工作
main.cpp
#include <iostream>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QNetworkInterface>
using namespace std;
int main()
{
QByteArray jsonString = "{\"ipaddr\": "+ QByteArray::number(9) + ",\"transactionType\":"+QByteArray::number(10) + ",\"idEmployee\":"+QByteArray::number(10) +"}";
QNetworkRequest request(QUrl("http://192.168.1.25:3000/classlog/pi"));
request.setRawHeader("Content-Type", "application/json");
QNetworkAccessManager * manager = new QNetworkAccessManager();
manager->post(request, jsonString);
}
.pro
TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
QT += network core
SOURCES += \
main.cpp
我希望我能够在服务器中接收请求,但是我什么也没收到。谢谢
答案 0 :(得分:2)
Qt使用事件系统。您的网络管理员将仅安排将在事件循环中处理的请求。这也是收到响应的地方。
您需要一个运行中的事件循环(实际上,一个QCoreApplication
对象,在执行代码时会收到警告)。
#include <QtNetwork>
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QNetworkAccessManager mgr;
QNetworkRequest req(QUrl("http://stackoverflow.com"));
auto *resp = mgr.get(req);
QObject::connect(resp, &QNetworkReply::finished, [&]() {
qDebug() << "FINISHED";
if (resp->error() != QNetworkReply::NoError)
qDebug() << "Error: " << resp->errorString();
else
qDebug() << "Status: " << resp->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString();
// Stop when a response is received
app.quit();
});
// This will start the event loop that will eventually send the request and receive the response.
// It will run until you call app.quit()
return app.exec();
}
答案 1 :(得分:0)
您快到了:
connect the signals:
QtObject::connect(your_manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(onResult(QNetworkReply *)));
send something:
QNetworkRequest request(your_URL);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QByteArray byteArray;
byteArray.append(your_json);
your_manager->post(request, byteArray);
read the answer in the slot:
void FOO_CLASS::onResult(QNetworkReply* reply)
{
QString resp = QString::fromUtf8(reply->readAll());
}
编辑 :
QObject::connect(your_manager, &QNetworkAccessManager::finished, [](QNetworkReply * r){
QString x{r->readAll()};
//foo1
auto l{x.length()};
//foo2
});