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

4 comments:

  1. I am using Qt5.4 to create a app for my embedded device. Is this sample works with my embedded device? Kind Regards

    ReplyDelete
    Replies
    1. Sorry, I have no experience with Qt on embedded devices

      Delete
  2. Tnx for your qt code. Is it possible to write the server side of a restful service in qt? Imagine that I want to pass the below json to the client.
    {
    "appDesc": {
    "description": "SomeDescription",
    "message": "SomeMessage"
    },
    "appName": {
    "description": "Home",
    "message": "Welcome",
    "imp":["awesome","best","good"]
    }
    }

    ReplyDelete
    Replies
    1. AFAIK there are no built-in support writing web services in QT, but there are plenty of implementations.
      e.g. http://stefanfrings.de/qtwebapp/index-en.html

      Delete