我正在关注此文档http://developer.nokia.com/community/wiki/Creating_an_HTTP_network_request_in_Qt尝试实现http连接并且我的代码编译时没有错误,但是当程序启动时,它会崩溃。
// coreeng.cpp
#include "coreeng.h"
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QImageReader>
coreEng::coreEng(QObject *parent) :
QObject(parent)
{
}
void coreEng::connect(){
QObject::connect(nam, SIGNAL(finished(QNetworkReply*)),
this, SLOT(finishedSlot(QNetworkReply*)));
}
void coreEng::url(){
QUrl url("http://www.forum.nokia.wiki");
QNetworkReply* reply = nam->get(QNetworkRequest(url));
}
void coreEng::finishedSlot(QNetworkReply* reply){
QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
QVariant redirectionTargetUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (reply->error() == QNetworkReply::NoError)
{
QImageReader imageReader(reply);
QImage pic = imageReader.read();
QByteArray bytes = reply->readAll(); // bytes
QString string(bytes); // string
}
else
{
}
delete reply;
}
// coreeng.h
#ifndef COREENG_H
#define COREENG_H
#include <QObject>
#include <QNetworkAccessManager>
class coreEng : public QObject
{
Q_OBJECT
public:
explicit coreEng(QObject *parent = 0);
private slots:
public slots:
void connect();
void url();
void finishedSlot(QNetworkReply* reply);
private:
QNetworkAccessManager* nam;
};
#endif // COREENG_H
// main.cpp中
#include <QCoreApplication>
#include "coreeng.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
coreEng mConnect;
mConnect.connect();
return a.exec();
}
答案 0 :(得分:0)
您应该更加关注您的c ++代码:
QNetworkAccessManager* nam;
nam
已使用但永远不会创建。您应该在coreEng
构造函数中创建它:
coreEng::coreEng(QObject *parent) :
QObject(parent), nam( new QNetworkAccessManager(this) )
{
}
另一个问题是:
delete reply;
Qt docs说:
请勿删除与此信号相连的插槽中的回复对象。使用deleteLater()。