EN ·
🌏 中文

Qt HTTP Server Example: Implementing Client POST and Server Response

Client-Side HTTP POST

Suppose http://127.0.0.1:8888/post/ is an endpoint that accepts POST requests. If we want to submit JSON data to this URL, we can implement it in Qt using QNetworkAccessManager as follows:

QCoreApplication app(argc, argv);
QNetworkAccessManager *mgr = new QNetworkAccessManager;
const QUrl url(QStringLiteral("http://127.0.0.1:8888/post/"));
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");

QJsonObject obj;
obj["key1"] = "value1";
obj["key2"] = "value2";
QJsonDocument doc(obj);
QByteArray data = doc.toJson();

QNetworkReply *reply = mgr->post(request, data);

QObject::connect(reply, &QNetworkReply::finished, [=](){
    if(reply->error() == QNetworkReply::NoError){
        QString contents = QString::fromUtf8(reply->readAll());
        qDebug() << contents;
    }
    else{
        QString err = reply->errorString();
        qDebug() << err;
    }
    reply->deleteLater();
    mgr->deleteLater();
});

Server-Side Implementation

The local server can be easily implemented using the QtHttpServer module:

QHttpServer http_server;
http_server.route("/", []() {
    return "Hello QtHttpServer";
});

http_server.route("/post/", QHttpServerRequest::Method::POST,
[](const QHttpServerRequest &request)
{
    qDebug() << "received requestBody" << request.body();
    return QJsonObject
    {
        {"message", "finish"}
    };
});

http_server.listen(QHostAddress::Any, 8888);

Source Code

The complete source code for both the client and the server is available on GitHub: qthttpserver-sample-with-client

References