Simple HTTP Server
Simple example of how to set up an HTTP server.
This example shows how to set up a server using the QHttpServer class. The server is bound to a QTcpServer listening to a port with the bind() function, and the route()
function is used to add a handler for each of several different incoming URLs. For one of the URLs, "/auth", Basic HTTP Authentication is used.
QSslConfiguration conf = QSslConfiguration::defaultConfiguration(); const auto sslCertificateChain = QSslCertificate::fromPath(QStringLiteral(":/assets/certificate.crt")); if (sslCertificateChain.empty()) { qWarning() << QCoreApplication::translate("QHttpServerExample", "Couldn't retrieve SSL certificate from file."); return -1; } QFile privateKeyFile(QStringLiteral(":/assets/private.key")); if (!privateKeyFile.open(QIODevice::ReadOnly)) { qWarning() << QCoreApplication::translate("QHttpServerExample", "Couldn't open file for reading: %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 failed to listen on a port."); return -1; } quint16 sslPort = sslserver->serverPort(); sslserver.release();
In the above example QSslConfiguration
is used to show how to create an SSL configuration for a QHttpServer to serve HTTPS traffic.
httpServer.addAfterRequestHandler(&httpServer, [](const QHttpServerRequest &, QHttpServerResponse &resp) { auto h = resp.headers(); h.append(QHttpHeaders::WellKnownHeader::Server, "Qt HTTP Server"); resp.setHeaders(std::move(h)); });
The above example shows how to use the addAfterRequestHandler()
function of the QHttpServer to change the QHttpServerResponse object after it has been handled by the route()
function. It demonstrates how HTTP headers can be added to the response.
Files:
Images:
© 2024 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.