【问题标题】:Dynamic parameter as part of request URI with Apache HttpCore使用 Apache HttpCore 作为请求 URI 一部分的动态参数
【发布时间】:2019-11-14 16:05:13
【问题描述】:

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

我的目标是定义一个 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())
       }
       [...]

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 谢谢!我将设法使其与HttpRequestHandlerMapper 一起使用
    猜你喜欢
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    相关资源
    最近更新 更多