Qt Console app using QNetworkAccessManager

大憨熊 提交于 2019-12-12 04:43:31

问题


I'm trying to write a Qt app that calls a web service. This is a console app, and url will be passed in as a command line argument. I searched for example http programs in Qt and found this link:

http://qt-project.org/doc/qt-5/qnetworkaccessmanager.html

Here it has the following code example:

QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),
        this, SLOT(replyFinished(QNetworkReply*)));

manager->get(QNetworkRequest(QUrl("http://qt-project.org")));

Now, if I take this and paste it into my console app, in main, I obviously get build errors because this does not exist. I get :

invalid use of 'this' in non-member function

Is there an equivalent QNetworkAccessManager for non-GUI/console type apps?


回答1:


"this" is the this pointer of an object, so in main.cpp it causes errors, you should write some class where you will work with network and after that use this class in main function

It should be something like this. When you run app, you'll get html code of Qt site

It is just example, in future we can add here constructot, destructor, maybe signals(signals help us communicate with for example other classes if we need this)

*.h

#ifndef NET_H
#define NET_H

#include <QObject>

#include <QtCore>
#include <QNetworkAccessManager>
#include <QNetworkReply>

class Net : public QObject
{
Q_OBJECT
  QNetworkAccessManager *manager;
private slots:
  void replyFinished(QNetworkReply *);
public:
  void CheckSite(QString url);
};



#endif // NET_H

*.cpp

#include "net.h"

void Net::replyFinished(QNetworkReply *reply) 
{ 
qDebug() << reply->readAll(); 
}

void Net::CheckSite(QString url) 
{
  QUrl qrl(url);
  manager = new QNetworkAccessManager(this);
  connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
  manager->get(QNetworkRequest(qrl));
}

main

#include "net.h"


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    Net handler;
    handler.CheckSite("http://qt-project.org");


    return a.exec();
}


来源:https://stackoverflow.com/questions/25433706/qt-console-app-using-qnetworkaccessmanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!