Einfacher HTTP-Server
Einfaches Beispiel für das Einrichten eines HTTP-Servers.
Dieses Beispiel zeigt, wie man einen Server mit der Klasse QHttpServer einrichtet. Der Server wird mit der Funktion bind() an eine QTcpServer gebunden, die auf einen Port hört, und die Funktion route()
wird verwendet, um einen Handler für jede der verschiedenen eingehenden URLs hinzuzufügen. Für eine der URLs, "/auth", wird die einfache HTTP-Authentifizierung verwendet.
QSslConfiguration conf = QSslConfiguration::defaultConfiguration();const auto sslCertificateChain =QSslCertificate::fromPath(QStringLiteral(":/assets/certificate.crt"));if (sslCertificateChain.empty()) { qWarning() << QCoreApplication::translate("QHttpServerExample", "Konnte das SSL-Zertifikat nicht aus der Datei abrufen."); return-1; }QFile privateSchlüsselDatei(QStringLiteral(":/assets/private.key"));if (!privateKeyFile.open(QIODevice::ReadOnly)) { qWarning() << QCoreApplication::translate("QHttpServerExample", "Die Datei konnte nicht zum Lesen geöffnet werden: %1") . arg(privateKeyFile.errorString()); return-1; } conf.setLocalCertificate(sslCertificateChain.front()); conf.setPrivateKey(QSslKey(&privateKeyFile, QSsl::Rsa)); privateKeyFile.close();auto sslserver = std::make_unique<QSslServer>(); sslserver->setSslConfiguration(conf);if (!sslserver->listen() || !httpServer.bind(sslserver.get())) { qWarning() << QCoreApplication::translate("QHttpServerExample", "Server konnte nicht auf einem Port lauschen."); return-1; }quint16 sslPort = sslserver->serverPort(); sslserver.release();
Im obigen Beispiel QSslConfiguration
wird gezeigt, wie eine SSL-Konfiguration für eine QHttpServer erstellt wird, um HTTPS-Verkehr zu bedienen.
httpServer.addAfterRequestHandler(&httpServer, [](const QHttpServerRequest &, QHttpServerResponse &resp) { auto h = resp.headers(); h.append(QHttpHeaders::WellKnownHeader::Server, "Qt HTTP Server"); resp.setHeaders(std::move(h)); });
Das obige Beispiel zeigt, wie man die Funktion addAfterRequestHandler()
von QHttpServer verwendet, um das Objekt QHttpServerResponse zu ändern, nachdem es von der Funktion route()
bearbeitet wurde. Es zeigt, wie HTTP-Header zur Antwort hinzugefügt werden können.
Dateien:
Bilder:
© 2025 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.