C++使用QtHttpServer开发服务端Server的Http POST接口和客户端Client示例

Client HTTP POST

假设http://127.0.0.1:8888/post/是一个能够接受POST请求的路径,我们想要向它提交一段json数据,用Qt可以这样实现:

Suppose we want to make an HTTP POST with json body to http://127.0.0.1:8888/post/.

cpp 复制代码
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();
});

Http Server

而这个本地的Server,亦可使用QtHttpServer方便实现:

Server can be implemented by QtHttpServer easily, too.

cpp 复制代码
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);

Code is available

Please refer to my project: qthttpserver-sample-with-client

Reference

How to send a POST request in Qt with the JSON body

qt-labs/qthttpserver

相关推荐
sthnyph1 天前
QT开发:事件循环与处理机制的概念和流程概括性总结
开发语言·qt
yangtuoni1 天前
vscode调试C++程序
c++·ide·vscode
m0_587958951 天前
C++中的命令模式变体
开发语言·c++·算法
西红市杰出青年1 天前
MCP 的三种数据传输模式教程(stdio / SSE / Streamable HTTP)
网络·网络协议·http·ai
.select.1 天前
HTTPS 如何优化?
网络协议·http·https
2501_924952691 天前
代码生成器优化策略
开发语言·c++·算法
fengenrong1 天前
20260324
c++·算法
qq_416018721 天前
设计模式在C++中的实现
开发语言·c++·算法
2301_776508721 天前
C++与机器学习框架
开发语言·c++·算法
ALex_zry1 天前
现代C++设计模式实战:从AIDC项目看工业级代码架构
c++·设计模式·架构