简单的HTTP服务器

关于如何搭建 HTTP 服务器的简单示例。

浏览器中显示的简单 HTTP 服务器输出

“简单 HTTP 服务器”演示了如何使用 `QHttpServer ` 类来搭建一个 HTTP 服务器。它监听两个套接字:一个 TCP 套接字和一个 SSL 套接字。通过设置不同的回调函数,演示了如何使用 `route()` 函数。

创建了一个QHttpServer 对象,一个简单的route()函数通过返回Hello world 来处理路径"/" :

QCoreApplication app(argc, argv);

QHttpServer httpServer;
httpServer.route("/", []() {
    return "Hello world";
});

然后,我们注册一个回调函数,用于向客户端提供服务器的资源:

httpServer.route("/assets/<arg>", [] (const QUrl &url) {
    return QHttpServerResponse::fromFile(u":/assets/"_s + url.path());
});

在此处,我们使用QHttpServerRequest 对象来获取客户端的IP地址:

httpServer.route("/remote_address", [](const QHttpServerRequest &request) {
    return request.remoteAddress().toString();
});

对于其中一个路径"/auth" ,使用了基本 HTTP 身份验证:

httpServer.route("/auth", [](const QHttpServerRequest &request) {
    auto auth = request.value("authorization").simplified();

    if (auth.size() > 6 && auth.first(6).toLower() == "basic ") {
        auto token = auth.sliced(6);
        auto userPass = QByteArray::fromBase64(token);

        if (auto colon = userPass.indexOf(':'); colon > 0) {
            auto userId = userPass.first(colon);
            auto password = userPass.sliced(colon + 1);

            if (userId == "Aladdin" && password == "open sesame")
                return QHttpServerResponse("text/plain", "Success\n");
        }
    }
    QHttpServerResponse resp("text/plain", "Authentication required\n",
                             QHttpServerResponse::StatusCode::Unauthorized);
    auto h = resp.headers();
    h.append(QHttpHeaders::WellKnownHeader::WWWAuthenticate,
             R"(Basic realm="Simple example", charset="UTF-8")");
    resp.setHeaders(std::move(h));
    return std::move(resp);
});

然后,我们使用addAfterRequestHandler() 函数,在QHttpServerResponse 对象经过route() 注册的回调处理后,通过向响应中添加 HTTP 头来对其进行修改:

httpServer.addAfterRequestHandler(&httpServer, [](const QHttpServerRequest &, QHttpServerResponse &resp) {
    auto h = resp.headers();
    h.append(QHttpHeaders::WellKnownHeader::Server, "Qt HTTP Server");
    resp.setHeaders(std::move(h));
});

通过bind() 函数,将监听某个端口的QTcpServer 与 HTTP 服务器绑定:

autotcpserver=std::make_unique<QTcpServer>();
if(!tcpserver->listen()|| !httpServer.bind(tcpserver.get())) {
    qWarning() << QCoreApplication::translate("QHttpServerExample",
                                             "服务器无法在该端口上监听。");
    return-1;
}
quint16 port= tcpserver->serverPort();
tcpserver.release();

然后使用 `QSslConfiguration ` 为 `QHttpServer ` 创建 SSL 配置,以处理 HTTPS 流量:

QSslConfiguration conf=QSslConfiguration::defaultConfiguration();
const autosslCertificateChain=
        QSslCertificate::fromPath(QStringLiteral(":/assets/certificate.crt"));
if(sslCertificateChain.empty()) {
    qWarning() << QCoreApplication::translate("QHttpServerExample",
                                             "无法从文件中读取 SSL 证书。");
    return-1;
}
QFile privateKeyFile(QStringLiteral(":/assets/private.key"));
if(!privateKeyFile.open(QIODevice::ReadOnly)) {
    qWarning() << QCoreApplication::translate("QHttpServerExample",
                                             "无法以读取方式打开文件:%1")
                  .arg(privateKeyFile.errorString());
    return-1;
}

conf.setLocalCertificate(sslCertificateChain.front());
conf.setPrivateKey(QSslKey(&privateKeyFile,QSsl::Rsa));
conf.setAllowedNextProtocols({ QSslConfiguration::ALPNProtocolHTTP2 });// 添加对 HTTP/2 的支持

privateKeyFile.close();

autosslserver=std::make_unique<QSslServer>();
sslserver->setSslConfiguration(conf);
if(!sslserver->listen()|| !httpServer.bind(sslserver.get())) {
    qWarning() << QCoreApplication::translate("QHttpServerExample",
                                             "服务器无法在该端口上监听。");
    return-1;
}
quint16 sslPort= sslserver->serverPort();
sslserver.release();

一切配置完成后,剩下的就是开始处理传入的请求了:

return app.exec();

文件:

图片:

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.