Simple Example | Qt HTTP Server 6.4.1

- Qt 6.4
- Qt HTTP Server
- Qt HTTP Server Examples
- Simple Example
- Qt 6.4.1 Reference Documentation

# Simple Example

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 an incoming port using the `listen()` 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.

     const auto sslCertificateChain =
             QSslCertificate::fromPath(QStringLiteral(":/assets/certificate.crt"));
     if (sslCertificateChain.empty()) {
         qDebug() << QCoreApplication::translate("QHttpServerExample",
                                                 "Couldn't retrive SSL certificate from file.");
         return 0;
     }
     QFile privateKeyFile(QStringLiteral(":/assets/private.key"));
     if (!privateKeyFile.open(QIODevice::ReadOnly)) {
         qDebug() << QCoreApplication::translate("QHttpServerExample",
                                                 "Couldn't open file for reading.");
         return 0;
     }
     httpServer.sslSetup(sslCertificateChain.front(), QSslKey(&privateKeyFile, QSsl::Rsa));
     privateKeyFile.close();

     const auto sslPort = httpServer.listen(QHostAddress::Any);
     if (!sslPort) {
         qDebug() << QCoreApplication::translate("QHttpServerExample",
                                                 "Server failed to listen on a port.");
         return 0;
     }

In the above example `QSslConfiguration` is used to show how to create an SSL configuration for a QHttpServer to serve HTTPS traffic.

Files:

- simple/CMakeLists.txt
- simple/assets.qrc
- simple/main.cpp
- simple/simple.pro

Images:

- simple/assets/qt-logo.png