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

相关推荐
MC皮蛋侠客5 小时前
Google Test 单元测试指南
c++·单元测试·google test
艾莉丝努力练剑6 小时前
【Linux:文件】Ext系列文件系统进阶
linux·运维·服务器·c++·文件系统·文件io·ext
eggcode6 小时前
【Qt学习】Linux(ARM架构)在线安装Qt6.x
linux·qt·学习·arm
basketball6168 小时前
C++ NULL 和 nullptr 区别 以及 nullptr 的核心实现
java·开发语言·c++
Fre丸子_9 小时前
自定义文件夹选取功能
c++
思麟呀11 小时前
C++工业级日志项目(六)异步日志器
linux·c++·windows
PAK向日葵11 小时前
从零实现 Python 虚拟机(二):S.A.A.U.S.O 的总体架构设计
c++·python
无限进步_11 小时前
【C++】weak_ptr、循环引用与线程安全
开发语言·数据结构·c++·算法·安全
咩咦12 小时前
C++学习笔记30:友元类、内部类和封装
c++·学习笔记·类和对象·封装·内部类·友元类·friend
黄小白的进阶之路13 小时前
C++提高编程---3.6 STL-常用容器-queue 容器【P213~P214】
c++