Sending Http Request Using Qt 5 framework

HTTP (Hypertext Transfer Protocol) works as a request-response protocol between a client and server. A web browser may be the client, and an application on a computer that hosts a web site may be the server. For example, a client (browser) submits an HTTP request to the server and then the server returns a response to the client. The response contains status information about the request as well as the requested content.

The two commonly used methods for a request-response between a client and server are: GET and POST.

  • GET - Requests data from a specified resource
  • POST - Submits data to be processed to a specified resource

The Qt framework provides the QNetworkRequest class as a part of the Network Access API that holds the information necessary to send a request over the network. As mentioned in the official API documentation, it contains a URL and some ancillary information that can be used to modify the request.

Through this post, we will learn how to send a HTTP GET request using the Qt 5 framework!

Pre-requisites: Qt Creator (Windows 64 bit), MinGW or VS compiler

Launch Qt creator IDE and create a new Qt console application project called HttpGetExample. Choose the default Desktop kit and leave the Add to Version control option as None. Now, let’s write the code in our main.cpp file as follows!

main.cpp

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

void sendRequest();

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    sendRequest();
    return a.exec();
}

void sendRequest(){

    // create custom temporary event loop on stack
    QEventLoop eventLoop;

    // "quit()" the event-loop, when the network request "finished()"
    QNetworkAccessManager mgr;
    QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));

    // the HTTP request
    QNetworkRequest req( QUrl( QString("http://ip.jsontest.com/") ) );
    QNetworkReply *reply = mgr.get(req);
    eventLoop.exec(); // blocks stack until "finished()" has been called

    if (reply->error() == QNetworkReply::NoError) {
        //success
        qDebug() << "Success" <<reply->readAll();
        delete reply;
    }
    else {
        //failure
        qDebug() << "Failure" <<reply->errorString();
        delete reply;
    }
}

You also need to make changes to the Project (.pro) file and add assign the corresponding values to variables.

.pro file

QT += core

QT -= gui

TARGET = HttpGetExample
CONFIG   += console
CONFIG   -= app_bundle
QT += network
TEMPLATE = app

SOURCES += main.cpp

Save all changes. Build and run the application. If no errors are present, then you should see the response of the HTTP request displayed in the console! :)

qt-http-get-output

That’s it for this small tip on Qt. Stay tuned for more! :)

Reference: Inside the Qt HTTP stack