我对C ++很新(虽然我有一些C经验)以及QT。我正在尝试在用户单击按钮时创建一个POST到网站的程序,但每当我尝试访问QNetworkManager时,我都会收到内存访问错误。
我的请求对象的代码如下(略微修剪以显示重要位):
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include "cJSON.h"
class unifiedRequests: public QObject {
Q_OBJECT
public:
// Members
QString access_token = "";
bool admin = false;
// Methods
explicit unifiedRequests(QObject *parent=0);
QNetworkReply* login_request(QString *email, QString *password);
signals:
public slots:
void login_complete(QNetworkReply *reply);
void sslErrorHandler(QNetworkReply*, const QList<QSslError> & );
private:
QNetworkRequest make_headers(QByteArray endpoint);
QNetworkRequest make_headers(QByteArray endpoint, QByteArray *access_token);
};
QNetworkRequest unifiedRequests::make_headers(QByteArray endpoint) {
QString url = endpoint.prepend("https://dali.vpt.co.uk");
QNetworkRequest request = QNetworkRequest(url);
qDebug() << "Setting Headers";
request.setRawHeader("User-Agent", "Desktop Client Debug");
request.setRawHeader("Content-Type", "application/json");
qDebug() << "Set headers successfully.";
return request;
}
void unifiedRequests::sslErrorHandler
(QNetworkReply* reply, const QList<QSslError> & errors) {
qDebug() << "Ignoring SSL Errors";
};
QNetworkReply* unifiedRequests::login_request
(QString *email, QString *password) {
QNetworkRequest request = make_headers("/api/auth");
qDebug() << "Making JSON";
cJSON *login_json; //The body of the request
login_json = cJSON_CreateObject();
cJSON_AddStringToObject(login_json, "email", email->toUtf8());
cJSON_AddStringToObject(login_json, "password", password->toUtf8());
qDebug() << "Made JSON: ";
qDebug() << cJSON_Print(login_json);
QNetworkAccessManager *manager = new QNetworkAccessManager;
//The object we use to send the request and receive the reply
qDebug() << "Turning off SSL";
connect(manager,
SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError> & )),
this,
SLOT(sslErrorHandler(QNetworkReply*, const QList<QSslError> & )));
qDebug() << "POSTing login.";
QNetworkReply *reply = manager->post(request, cJSON_Print(login_json));
qDebug() << "Connecting signal to slot.";
QAbstractSocket::connect(manager, SIGNAL(finished(QNetworkReply * )),
this, SLOT(login_complete(QNetworkReply * )));
cJSON_Delete(login_json);
return reply;
}
我正在通过调用:
创建unifiedRequests对象unifiedRequests requestObj;
在另一个文件中。它在我尝试关闭SSL的行上崩溃(我们使用的是自签名证书,所以我需要这样做才能发出请求)。有什么想法吗? 谢谢!
答案 0 :(得分:2)
您通过调用&#34; unifiedRequests requestObj;&#34;来创建unifiedRequests对象,当变量&#34; requestObj&#34;超出范围。
因此,当接收到信号时,对象将被破坏。
尝试通过调用&#34; unifiedRequests * requestObj = new unifiedRequests();&#34;来创建unifiedRequests对象。
当然,您需要拨打&#34;删除requestObj;&#34;在某处摧毁这个物体。何时何地取决于您的申请(当您不再需要此对象时)。
要了解其中的差异,请查看此处:http://www.tutorialspoint.com/cplusplus/cpp_dynamic_memory.htm
或google for&#34; C ++堆/堆栈/动态分配&#34;