我是 QT 开发的新手,我必须制作一个非 GUI 应用程序,它从 a 读取令牌POST request
,然后json requests
使用该令牌启动一些。我的问题是启动时该怎么办finished signal
。我试图将 传递reply.readAll()
给QByteArray
对象的参数,但是当我这样做时,值始终为空(“”)。我的代码是基于this完成的。
。H
#ifndef DOWNLOADER_H
#define DOWNLOADER_H
#include <QObject>
#include <QNetworkAccessManager>
class QNetworkReply;
class Downloader : public QObject
{
Q_OBJECT
public:
Downloader(QObject* parent=0);
void test();
bool finished = false;
QByteArray data;
public slots:
void handleReply(QNetworkReply* reply);
protected:
QNetworkAccessManager m_manager;
};
#endif // DOWNLOADER_H
.cpp
#include "downloader.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QVariant>
#include <QDebug>
Downloader::Downloader(QObject *parent) :
QObject(parent)
{
connect(&m_manager, SIGNAL(finished(QNetworkReply*)), SLOT(handleReply(QNetworkReply*)));
}
void Downloader::test() {
QNetworkRequest request;
QUrl url("http://192.168.25.25:8080/path/to/token");
QUrl postData;
postData.addQueryItem("client_id", "foo");
postData.addQueryItem("username", "bar");
postData.addQueryItem("password", "12345");
postData.addQueryItem("grant_type", "password");
request.setUrl(url);
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
QNetworkReply* rep = m_manager.post(request,postData.encodedQuery());
rep->setProperty("url", QVariant(url));
qDebug() << "Post " << rep << rep->url();
}
void Downloader::handleReply(QNetworkReply *reply) {
qDebug() << "Handle" << reply << reply->url();
qDebug() << "Dynamic property" << reply->property("url").isValid() << reply->property("url");
qDebug() << "ReadAll " << reply->readAll();
finished = true;
data =reply->readAll();
reply->deleteLater();
}
主要是调用:
Downloader down;
down.test();
while (!down.finished)
{
usleep(3*1000*1100);//3,3s
cout << "no finalizado";
}
我想要做的是使用来填充参数并使用来自的reply
这个参数main
,当. 我知道这是不正确的,但我不知道如何管理请求的异步性质。我需要的是一些指南来了解我在做什么,因为我一直在 qt 页面、stackoverflow 和其他人中搜索但没有成功。提前致谢。finished bool
true
更新:我的主要功能
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Downloader down;
down.test();
return a.exec();
}