我写了一段代码,通过邮件请求将json发送给我的API Rest;并且有效!
的main.cpp
void replyFinished(QNetworkReply *reply)
{
reply->deleteLater();
qDebug() << "reply delete!";
qDebug() << "https post_request done!";
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QNetworkAccessManager *manager = new QNetworkAccessManager();
QUrl url("https://.../");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QObject::connect(manager, &QNetworkAccessManager::finished, replyFinished);
quint8 speed = 0x12;
quint8 accelleration = 0x2b;
QString json = QString("{\"speed\":\"%1\",\"acceleration\":\"%2\"}").arg(speed).arg(accelleration);
manager->post(request, json.toUtf8());
return a.exec();
}
但是当我想在我的程序中集成这段代码时,它不起作用。简而言之,我的程序通过SIGNAL和SLOT机制,一个QByteArray,我从中获取数据并将它们发送到我的API Rest。
这是我的 Header.h
...
class Packet : public QObject
{
Q_OBJECT
public:
Packet();
public slots:
void receivePayload(QByteArray &bufferToJson);
void replyFinished(QNetworkReply *reply);
private:
QNetworkAccessManager *m_manager;
quint8 m_speed;
quint8 m_accelleration;
public:
QString json;
};
...
这是我的 class.cpp
Packet::Packet()
: m_manager { new QNetworkAccessManager }
{
QObject::connect(m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
}
void Packet::replyFinished(QNetworkReply *reply)
{
reply->deleteLater();
qDebug() << "reply delete!";
qDebug() << "https post_request done!";
}
void Packet::receivePayload(QByteArray &bufferToJson){
m_speed = bufferToJson.at(0);
m_accelleration = bufferToJson.at(1);
QUrl url("https://.../");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QString json = QString("{\"speed\":\"%1\",\"acceleration\":\"%2\"}").arg(m_speed).arg(m_accelleration);
m_manager->post(request, json.toUtf8());
}
我的改变有什么问题?