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.
QT += network
Next you have to add QtNetwork header files to your source code using the line below.
Now you need to create a request using the specific URL for that web service or API.
You have to set the request header content type as seen below:
Then you have to create your JSON request. (What is shown here is just an example and not a real JSON request.)
Now you have to create a Network Access object which will help with sending the request.
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.
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: