シンプルなHTTPサーバー
HTTPサーバーのセットアップ方法の簡単な例です。
この例では、QHttpServer クラスを使用してサーバーをセットアップする方法を示します。サーバはbind()関数でポートをリッスンしているQTcpServer にバインドされ、route()
関数を使用して、いくつかの異なる受信URLのそれぞれにハンドラを追加します。URLの1つである"/auth "では、Basic HTTP認証が使用される。
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(&privateKeyFile、 QSsl::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();
上記の例では、QSslConfiguration
を使用して、QHttpServer で HTTPS トラフィックを提供するための SSL 構成を作成する方法を示しています。
httpServer.addAfterRequestHandler(&httpServer, [](const QHttpServerRequest &, QHttpServerResponse &resp) { auto h = resp.headers(); h.append(QHttpHeaders::WellKnownHeader::Server, "Qt HTTP Server"); resp.setHeaders(std::move(h)); });
上記の例では、QHttpServer のaddAfterRequestHandler()
関数を使用して、route()
関数で処理された後にQHttpServerResponse オブジェクトを変更する方法を示しています。レスポンスにHTTPヘッダーを追加する方法を示しています。
ファイル
画像
© 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.