Question

I'm really nooby with C++ (as my previous posts mention), however my friend suggested I work with QNetworkAccessManager if I want to send a HTTP GET request to send information.

I am currently working with openGL-es and want to do the following two lines of code to send the get request:

QNetworkAccessManager* netMan = new QNetworkAccessManager(this);
netMan->get(QNetworkRequest(QUrl("something/?userID=1")));

However, it does not like the "this" because it is in the main() method and it does not reference a QObject (I'm guessing QApplication). When I get rid of the "this" my application builds, but just never loads (I put a "printf(1)" at the top which doesn't even run).

Any suggestions or alternatives on how to fix this? Thanks in advance.

-James

Was it helpful?

Solution

The parameter in the QNetworkAccessManager constructor is only needed to specify a QObject based parent which will be responsible for cleaning up (deleting) your object later and isn't necessary if you plan to call delete on it yourself.

I'm not quite sure what you are referring to by "never loads" or where you put a printf but in order to get anything back, you need to actually keep the QNetworkReply pointer that is returned by the call to get().

And to get anything from that, you need an event loop running. If your application is console only (no GUI), you can use a QCoreApplication object.

Try this minimal code:

#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QNetworkAccessManager *netMan = new QNetworkAccessManager();
    QNetworkReply *reply = netMan->get(QNetworkRequest(QUrl("http://google.com")));
    a.connect(reply, SIGNAL(finished()), SLOT(quit()));
    a.exec();
    qDebug() << reply->readAll();
    delete netMan;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top