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:
find_package(Qt6 COMPONENTS Network REQUIRED)
target_link_libraries(ZcAnimeDanmuTool PRIVATE Qt6::Network)Then add in your .h:
#include <QNetworkAccessManager>And declare a manager in private:
QNetworkAccessManager *m_manager;Usage
GET request
This example uses an event loop in a straightforward way.
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 memoryread is the response content. It is usually JSON and needs further processing.
POST request
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
No comments yet
Share your thoughts and keep the conversation clear and kind.
Write a comment
Sign in with GitHub first, then you can comment.