How to Send and Receive JSON Requests in Qt

There are many APIs on the web that accept JSON requests and reply using JSON. An example for this can be most of Google’s API services. For example if you are writing a Qt application that needs JSON interaction with a Google API (such as Google Webmaster API) you can easily send requests and receive responses if you follow these steps.



First of all make sure that your Qt project is using network module by adding the following line to your .pro file.

Next you have to add QtNetwork header files to your source code using the line below.

#include <QtNetwork>

Now you need to create a request using the specific URL for that web service or API.

QNetworkRequest request(QUrl("http://example.com/exampleapi"));

You have to set the request header content type as seen below:

request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

Then you have to create your JSON request. (What is shown here is just an example and not a real JSON request.)

QJsonObject json;
body.insert("item1", "value1");
body.insert("item2", "value2");


Now you have to create a Network Access object which will help with sending the request.

QNetworkAccessManager nam;

And send (POST) your JSON request. Result will be saved in a QNetworkRply

QNetworkReply *reply = nam.post(request, QJsonDocument(json).toJson());

You have to wait for the response from server.

while (!reply->isFinished())
{
	qApp->processEvents();
}

When server sends you the response, you have to store it like this:

QByteArray response_data = reply->readAll();

Assuming that the response is a JSON object you can change its format like this:

QJsonDocument json = QJsonDocument::fromJson(response_data);

One last thing to note is that you have to clean up the reply object by yourself using the line below:

reply->deleteLater();


10 Replies to “How to Send and Receive JSON Requests in Qt”

  1. Hello Amin,

    i wouldn’t use:

    while (!reply->isFinished())
    {
    qApp->processEvents();
    }

    it’s better to:

    connect(RequestManager, SIGNAL(finished(QNetworkReply*)),this, SLOT(Downloaded(QNetworkReply*)));

  2. I received a QNetworkReply::NetworkError(ConnectionRefusedError) error where could that potentially be coming from?

    1. It can have many different reasons.
      Use a tool such as Postman to make sure your endpoint is working.
      Make sure you wait using the while loop mentioned before readAll.
      Hope this helps.

  3. It is showing the bellow error:
    /var/www/qt_apps/Tracker/mainwindow.cpp:30: error: request for member ‘setHeader’ in ‘request’, which is of non-class type ‘QNetworkRequest(QUrl)’
    request.setHeader(QNetworkRequest::ContentTypeHeader, “application/json”);
    ^

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.