首页 > 解决方案 > 使用 Apache HttpCore 作为请求 URI 一部分的动态参数

问题描述

我正在寻找将动态参数与 HttpCore 匹配的现有解决方案。我想到的是类似于 ruby​​ on rails 中的约束,或带有风帆的动态参数(例如,请参见此处)。

我的目标是定义一个 REST API,我可以在其中轻松匹配GET /objects/<object_id>.

为了提供一点上下文,我有一个HttpServer使用以下代码创建的应用程序

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

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

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())
       }
       [...]

当然,我可以path.equals("/object/add")用 RegEx 替换更复杂的东西来匹配这些动态参数,但在这样做之前,我想知道我是否没有重新发明轮子,或者是否存在我没​​有看到的现有库/类可以帮助我的文档。

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

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

标签: apache-httpclient-4.xapache-httpcomponents

解决方案


目前 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();

推荐阅读