我正在尝试将页面从服务器下载到我的 QT 程序,但我一直在寻找方法,但它们并没有真正发挥作用。我不是 QT/C++ 方面的专家,所以请善待 :)
好吧..到目前为止,我使用了以下代码:
[旧代码] - 检查下面的更新代码!
http.cpp
#include "http.h"
http::http(QObject *parent) :
QObject(parent)
{
qDebug() << "HTTP ST";
http1 = new QHttp(this);
connect(http1, SIGNAL(done(bool)), this, SLOT(httpdown())); // Correction 1.
http1->setHost("localhost");
http1->get("/test.php");
qDebug() << "HTTP END";
}
void http::httpdown()
{
qDebug() << "completed!";
qDebug() << http1->readAll();
}
http.h
#ifndef HTTP_H
#define HTTP_H
#include <QtNetwork>
#include <QHttp>
#include <QDebug>
#include <QObject>
class http : public QObject
{
Q_OBJECT
public:
explicit http(QObject *parent = 0);
signals:
public slots:
void httpdown();
private:
QHttp *http1;
};
#endif // HTTP_H
好吧,问题是从来没有调用过 httpdown() ,而且我已经尝试了我所知道的任何事情:( 可能我没有正确执行此操作。
帮助将不胜感激。谢谢。
问题更新
我已经听取了alexisdm的建议并检查了 QNetworkAccessManager。所以这里是在 main() 上正确工作的新代码。
当我从另一个班级运行它时,我永远不会收到信号。
[新代码]
http2.cpp
#include "http2.h"
http2::http2(QObject *parent) :
QObject(parent)
{
m_manager = new QNetworkAccessManager(this);
connect(m_manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(httpdown(QNetworkReply*)));
QNetworkRequest request;
request.setUrl(QUrl("http://localhost/test.php"));
request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
m_manager->get(request);
}
void http2::httpdown(QNetworkReply* result)
{
QByteArray data= result->readAll();
QString str(data);
qDebug() << str;
}
http2.h
#ifndef HTTP2_H
#define HTTP2_H
#include <QObject>
#include <QDebug>
#include <QtNetwork>
#include <QNetworkReply>
class http2 : public QObject
{
Q_OBJECT
public:
explicit http2(QObject *parent = 0);
signals:
public slots:
void httpdown(QNetworkReply* result);
private:
QNetworkAccessManager* m_manager;
};
#endif // HTTP2_H
现在,如果我像这样直接在 main.cpp 下调用它:
主文件
#include <QtCore/QCoreApplication>
#include "tcpserver.h"
#include "http2.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
http2 h; // --> Working!!
tcpserver mServer;
return a.exec();
}
它工作正常。但是,如果我在 tcpserver 类中这样调用它:
tcpserver.cpp
#include "tcpserver.h"
#include "protocol.h"
#include "http2.h"
QTextStream in(stdin);
tcpserver::tcpserver(QObject *parent) :
QObject(parent)
{
server = new QTcpServer(this);
[ ... Other Server Stuff ... ]
// http2 h; // --> OLD CODE - Not Working :(
http2 *h = new http2(this); // **--> NEW CODE working provided by alexisdm**
}
信号永远不会发生...怎么了?我是新来的!:P
无论如何,alexisdm 说:“也许 http 对象在发出信号之前就被破坏了(例如,如果它是在堆栈上分配的)” -解决方案接受,代码如下更正阅读:QT C++ - 需要 QNetworkAccessManager 帮助!课堂问题(答案链接)
我应该怎么做才能避免这种情况?
谢谢!;)