Sunday, October 4, 2015

Consuming a RESTful Web Service with C++ using QT libraries

After a long time I got a chance to work again with QT framework, Here are some of the findings about how to invoke RESTful webservices using QT. It's pretty easy really!!

requirements
g++  or compatible c++ compiler
QT5 or later with QtNetwork module

source
main.cpp
#include <QCoreApplication>
#include <QtCore/QUrl>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QEventLoop eventLoop;
    QNetworkAccessManager mgr;
    QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    QNetworkRequest req( QUrl( QString("http://api.openweathermap.org/data/2.5/weather?q=colombo,lk") ) );
    QNetworkReply *reply = mgr.get(req);
    eventLoop.exec();

    if (reply->error() == QNetworkReply::NoError) {
        QString strReply = (QString)reply->readAll();
        QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
        QJsonObject jsonObj = jsonResponse.object();
        qDebug() << "name: " << jsonObj["name"].toString();
        qDebug() << "latitude: " << jsonObj.value(QString("coord")).toObject()["lat"].toDouble();
        qDebug() << "longitude: " << jsonObj.value(QString("coord")).toObject()["lon"].toDouble();
        delete reply;
    }
    else {
        qDebug() << "Failure" <<reply->errorString();
        delete reply;
    }
    return 0;
}

compile 
g++ -c -m64 -pipe -O2 -Wall -W -D_REENTRANT -fPIE -DQT_NO_DEBUG -DQT_NETWORK_LIB -DQT_CORE_LIB -I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++-64 -I. -I/usr/include/qt5 -I/usr/include/qt5/QtNetwork -I/usr/include/qt5/QtCore -I. -o main.o main.cpp

link
g++ -m64 -Wl,-O1 -o jsonWSClinetTest main.o   -lQt5Network -L/usr/lib/x86_64-linux-gnu -lQt5Core -lpthread 

output
name: "Colombo"
lat: 6.93
lat: 79.85