Search code examples
qtqnetworkaccessmanagerqnetworkrequest

Qt QNetworkAccessManager & simple web service return


I have a simple web service with the following URL:

http://localhost:8080/WebSvc1/webresources/generic/data?ctype=Ping

This returns a simple XML data:

<CALL TYPE='Ping'><IP>10.0.0.10</IP></CALL>

I'm trying to write a Qt program to call this web service.

The code that makes the call is below:

  QUrl qrl("http://localhost:8080/WebSvc1/webresources/generic/data?ctype=Ping");
  manager = new QNetworkAccessManager(this);
  connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
  printf ("Calling url: [%s]\n", qPrintable(url));
  QNetworkReply *reply = 0;
  reply = manager->get(QNetworkRequest(qrl));
  qDebug() << reply->readAll();

I'm expecting/hoping the readAll will get the XML text data and print it (via qDebug).

Instead I see nothing and the program just hangs.

UPpdate, also have this:

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

Solution

  • I've included an example (forcing a synchronous request <-> reply exchange to easy the debugging process) that should work for you:

    QUrl qrl("http://localhost:8080/WebSvc1/webresources/generic/data?ctype=Ping");
    qDebug() << "Calling url: " << qrl.toString();
    manager = new QNetworkAccessManager();
    QNetworkReply* reply = manager->get(QNetworkRequest(qrl));
    QEventLoop eventLoop;
    connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec();
    if (reply->error() != QNetworkReply::NoError)
    {
        qDebug() << "Network error: " << reply->error();
    }
    else
    {
        qDebug() << reply->readAll();
    }
    

    Notice that the "emitter" of the finished signal is not the QNetworkAccessManager but the reply itself.