Using HTTP GET and POST in Qt

How to send GET and POST requests in Qt

Brief intro

The Hypertext Transfer Protocol (HTTP) is designed to ensure communication between clients and servers.

HTTP works as a request-response protocol between a client and a server.

A web browser can be a client, and network applications on a computer can be servers.

Example: a client (browser) submits an HTTP request to a server; the server returns a response. The response contains status information about the request and possibly the requested content.

Two HTTP request methods: GET and POST.
When communicating between client and server, the two most common methods are GET and POST.

GET - requests data from a specified resource.
POST - submits data to be processed to a specified resource.
GET parameters are usually shown in the URL. POST submits via a form and does not show in the URL, so POST is more private.

Preparation

You need to add Network-related modules to your project.

CMake example:

1
2
find_package(Qt6 COMPONENTS Network REQUIRED)
target_link_libraries(ZcAnimeDanmuTool PRIVATE Qt6::Network)

Then add in your .h:

1
#include <QNetworkAccessManager>

And declare a manager in private:

1
QNetworkAccessManager *m_manager;

Usage

GET request

This example uses an event loop in a straightforward way.

1
2
3
4
5
6
7
m_manager = new QNetworkAccessManager(this); // create QNetworkAccessManager
QEventLoop loop; // event loop
QNetworkReply *reply = m_manager->get(QNetworkRequest(QUrl("url"))); // target URL
connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); // bind reply event
loop.exec(); // wait for reply
QString read = reply->readAll();
reply->deleteLater(); // free memory

read is the response content. It is usually JSON and needs further processing.

POST request

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
QNetworkRequest request;
// header settings
request.setUrl(QUrl("url")); // target URL
request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json")); // example header
// body settings
QJsonObject jsonObj;
/* fill json content as needed */
QJsonDocument jsonDoc(jsonObj);
// send POST request
QEventLoop loop;
QNetworkReply* reply = naManager->post(request, jsonDoc.toJson());
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec(); // wait for reply
QString read;
read = reply->readAll();
reply->deleteLater(); // free memory

Using HTTP GET and POST in Qt
https://greatzaochen.dev/en/posts/32b33793/
Author
Zao_chen
Posted on
October 28, 2024
Licensed under