apache-httpclient-4.x - 使用 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,但我可以升级到更新版本的这可能对我有帮助。
解决方案
目前 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();
推荐阅读
- redux - Redux 在使用 mapDispatchToProps 初始化之前无法访问 action creator
- amazon-web-services - AWS 无服务器:从无服务器迁移到 SAM
- javascript - 使用嵌套的 try-catch 块
- python - ipywidgets clear_output() 在第二次使用时不起作用
- pg-promise - pg-promise 会自动关闭连接吗?
- mysql - 您可以在 where 子句中使用 select 语句的结果吗?
- swift - Swift - 对 Firebase 存储中的结果进行排序
- wpf - 根据值更改单元格颜色
- r - tidyverse 方法来创建复合度量
- asp.net-core - 验证 Azure Active Directory 中是否存在用户帐户