作为Apache HttpCore请求URI的一部分的动态参数

问题描述 投票:0回答:1

我正在寻找现有的解决方案,以将动态参数与HttpCore进行匹配。我想到的是类似于在轨道上的红宝石约束或带有风帆的动态参数(例如,请参见here)。

我的目标是定义一个REST API,使我可以轻松地匹配GET /objects/<object_id>之类的请求。

为了提供一些背景信息,我有一个使用以下代码创建HttpServer的应用程序

server = ServerBootstrap.bootstrap()
            .setListenerPort(port)
            .setServerInfo("MyAppServer/1.1")
            .setSocketConfig(socketConfig)
            .registerHandler("*", new HttpHandler(this))
            .create();

以及与所请求的URI匹配的HttpHandler类,并将其分派到相应的后端方法:

public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) {

        String method = request.getRequestLine().getMethod().toUpperCase(Locale.ROOT);
        // Parameters are ignored for the example
        String path = request.getRequestLine().getUri();
       if(method.equals("POST") && path.equals("/object/add") {
           if(request instanceof HttpEntityEnclosingRequest) {
           addObject(((HttpEntityEnclosingRequest)request).getEntity())
       }
       [...]

确保我可以用RegEx用更复杂的东西替换path.equals("/object/add")来匹配这些动态参数,但是在这样做之前,我想知道我是不是在重新发明轮子,还是我有一个现有的lib / class没有在文档中找到可以帮助我的信息。

使用HttpCore是必需的(它已经集成在我正在开发的应用程序中),我知道其他一些库提供了支持这些动态参数的高级路由机制,但是我真的负担不起切换整个服务器代码到另一个图书馆。

我目前正在使用httpcore 4.4.10,但是我可以升级到较新的版本可能会对我有所帮助。

apache-httpclient-4.x apache-httpcomponents
1个回答
0
投票

目前HttpCore没有功能齐全的请求路由层。 (这样做的原因是政治性而非技术性。)>

考虑使用自定义HttpRequestHandlerMapper来实现您的应用程序特定的请求路由逻辑。

final HttpServer server = ServerBootstrap.bootstrap()
        .setListenerPort(port)
        .setServerInfo("Test/1.1")
        .setSocketConfig(socketConfig)
        .setSslContext(sslContext)
        .setHandlerMapper(new HttpRequestHandlerMapper() {

            @Override
            public HttpRequestHandler lookup(HttpRequest request) {
                try {
                    URI uri = new URI(request.getRequestLine().getUri());
                    String path = uri.getPath();
                    // do request routing based on the request path
                    return new HttpFileHandler(docRoot);

                } catch (URISyntaxException e) {
                    // Provide a more reasonable error handler here
                    return null;
                }
            }

        })
        .setExceptionLogger(new StdErrorExceptionLogger())
        .create();
© www.soinside.com 2019 - 2024. All rights reserved.