下面是一个使用QHttpServer的简单示例。
#include <QtCore>
#include <QtHttpServer>
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QHttpServer httpServer;
httpServer.route("/", []() {
return "Hello world";
});
httpServer.route("/test/", []() {
return "test";
});
httpServer.afterRequest([](QHttpServerResponse &&resp) {
resp.setHeader("Server", "Super server!");
return std::move(resp);
});
const auto port = httpServer.listen(QHostAddress::Any);
if (!port) {
qDebug() << QCoreApplication::translate(
"QHttpServerExample", "Server failed to listen on a port.");
return 0;
}
qDebug() << QCoreApplication::translate(
"QHttpServerExample", "Running on http://127.0.0.1:%1/ (Press CTRL+C to quit)").arg(port);
return app.exec();
}
运行代码后,您可以在浏览器中输入以下网址,
世界你好
测试
我的目的是在一个函数中捕获所有请求——即使是任意子网址,例如
我如何获取这些网址?
我向AI询问了此事。它指向
QHttpRequest
,但我的 Qt 库中没有这样的东西。而且我也查了Qt文档,不存在。
感谢@m7913d的提醒。我发现了这个,
server.setMissingHandler([](const QHttpServerRequest& request,
QHttpServerResponder&& responder) {
request.url();
});