シンプルなHTTPサーバー

HTTPサーバーのセットアップ方法の簡単な例です。

Simple HTTP Server はQHttpServer クラスを使って HTTP サーバをセットアップする方法を示しています。TCPソケットとSSLソケットの2つのソケットをリッスンします。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();
});

パスの1つ、"/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);
});

次に、レスポンスにHTTPヘッダーを追加することで、route ()で登録されたコールバックによって処理された後、addAfterRequestHandler ()関数を使用してQHttpServerResponse オブジェクトを変更する:

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

あるポートをリッスンしているQTcpServer は、bind() 関数を使ってHTTPサーバーにバインドされる:

autotcpserver=std::make_unique<QTcpServer>();if(!tcpserver->listen()|| !httpServer.bind(tcpserver.get())){    qWarning() << QCoreApplication::translate("QHttpServerExample",
                                             "Server failed to listen on a port.");return -1; }.quint16port=  tcpserver->serverPort(); tcpserver.release();

そして、QSslConfiguration 、HTTPSトラフィックを提供するためのSSLコンフィギュレーションをQHttpServer

QSslConfigurationconf=QSslConfiguration::defaultConfiguration();const autosslCertificateChain=QSslCertificate::fromPath(QStringLiteral(":/assets/certificate.crt"));if(sslCertificateChain.empty()) { {if(sslCertificateChain.empty())    qWarning() << QCoreApplication::translate("QHttpServerExample",
                                             "ファイルからSSL証明書を取得できませんでした。");return -1; }.QFileprivateKeyFile(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(&privateKeyFileQSsl::Rsa)); privateKeyFile.close();autosslserver=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; }.quint16sslPort=  sslserver->serverPort(); sslserver.release();

すべてのセットアップが完了したら、あとはリクエストの処理を開始するだけです:

return app.exec();

ファイル

画像

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