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

相关推荐
挥剑决浮云 -10 分钟前
QT信号槽 笔记
开发语言·笔记·qt
I"ll carry you1 小时前
【C++基础】enum,union,uint8_t,static
java·数据库·c++
Zfox_1 小时前
【Linux】应用层自定义协议与序列化
linux·服务器·c语言·c++
*TQK*2 小时前
C++/C语言判断重复数组(zznu)⭐
c语言·数据结构·c++
赛博之心2 小时前
C++系列之static关键字
c++
bigsea763 小时前
mongoose 支持https踩坑纪实
网络协议·http·https
可涵不会debug3 小时前
Git在码云上的使用指南:从安装到推送远程仓库
linux·运维·服务器·c++·git
Flocx3 小时前
联合体(Union)
开发语言·网络·c++·stm32
迂幵myself3 小时前
14-1C++STL的初始
开发语言·c++
羑悻的小杀马特4 小时前
【狂热算法篇】探秘图论之 Floyd 算法:解锁最短路径的神秘密码(通俗易懂版)
c++·算法·图论·floyd算法