Servidor HTTP simples

Exemplo simples de como configurar um servidor HTTP.

Saída simples de um servidor HTTP no navegador

O Servidor HTTP Simples mostra como configurar um servidor HTTP usando a classe ` QHttpServer `. Ele escuta em dois soquetes: um soquete TCP e um soquete SSL. Diferentes callbacks são configurados para demonstrar como usar a função ` route()`.

É criado um objeto ` QHttpServer `, e uma chamada de retorno simples ` route()` lida com o caminho ` "/" `, retornando ` Hello world`:

QCoreApplication app(argc, argv);

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

Em seguida, registramos uma chamada de retorno que fornece os recursos do servidor ao cliente:

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

Aqui, usamos o objeto ` QHttpServerRequest ` para retornar o endereço IP do cliente:

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

Para uma das rotas, "/auth", é utilizada a autenticação HTTP básica:

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);
});

Em seguida, usamos a função addAfterRequestHandler() para alterar o objeto QHttpServerResponse após ele ter sido processado pelos callbacks registrados por route(), adicionando cabeçalhos HTTP à resposta:

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

Um ` QTcpServer ` que escuta em uma porta é vinculado ao servidor HTTP por meio da função ` bind()`:

auto tcpserver = std::make_unique<QTcpServer>();
if (!tcpserver->listen()|| !httpServer.bind(tcpserver.get())) {
    qWarning() << QCoreApplication::translate("QHttpServerExample",
                                             "O servidor não conseguiu escutar em uma porta.");
    return-1;
}
quint16 port = tcpserver->serverPort();
tcpserver.release();

Em seguida, o ` QSslConfiguration ` é usado para criar uma configuração SSL para um ` QHttpServer ` a fim de atender ao tráfego HTTPS:

QSslConfiguration conf = QSslConfiguration::defaultConfiguration();
const auto sslCertificateChain =
        QSslCertificate::fromPath(QStringLiteral(":/assets/certificate.crt"));
if (sslCertificateChain.empty()) {
    qWarning() << QCoreApplication::translate("QHttpServerExample",
                                             "Não foi possível recuperar o certificado SSL do arquivo.");
    return-1;
}
QFile privateKeyFile(QStringLiteral(":/assets/private.key"));
if (!privateKeyFile.open(QIODevice::ReadOnly)) {
    qWarning() << QCoreApplication::translate("QHttpServerExample",
                                             "Não foi possível abrir o arquivo para leitura: %1")
                  .arg(privateKeyFile.errorString());
    return-1;
}

conf.setLocalCertificate(sslCertificateChain.front());
conf.setPrivateKey(QSslKey(&privateKeyFile, QSsl::Rsa));
conf.setAllowedNextProtocols({ QSslConfiguration::ALPNProtocolHTTP2 }); // Adicionar suporte a HTTP/2

privateKeyFile.close();

auto sslserver = std::make_unique<QSslServer>();
sslserver->setSslConfiguration(conf);
if (!sslserver->listen()|| !httpServer.bind(sslserver.get())) {
    qWarning() << QCoreApplication::translate("QHttpServerExample",
                                             "O servidor não conseguiu escutar em uma porta.");
    return-1;
}
quint16 sslPort = sslserver->serverPort();
sslserver.release();

Depois que tudo estiver configurado, basta começar a processar as solicitações recebidas:

return app.exec();

Arquivos:

Imagens:

© 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.