如何在过滤器方法中使用 ContainerRequestContext 获取 REST api 的有效负载
How to get the payload of REST api using ContainerRequestContext in filter method
我有一个过滤器,POST REST api 与之配合使用,我想在过滤器中提取我的负载的以下部分。
{
"foo": "bar",
"hello": "world"
}
过滤代码:-
public class PostContextFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext)
throws IOException {
String transactionId = requestContext.getHeaderString("id");
// Here how to get the key value corresponding to the foo.
String fooKeyVal = requestContext. ??
}
}
我没有看到任何简单的方法可以使用 ContainerRequestContext
对象将有效负载发送到 api。
所以我的问题是如何在我的有效负载中获取与 foo 键对应的键值。
虽然过滤器主要用于操纵请求和响应参数,如 HTTP headers、URI and/or HTTP 方法,但拦截器旨在通过操纵实体 input/output 流来操纵实体。
A ReaderInterceptor
允许您操纵 入站 实体流,即来自 来自 [=24] 的流=].使用 Jackson 解析入站实体流,你的拦截器可能是这样的:
@Provider
public class CustomReaderInterceptor implements ReaderInterceptor {
// Create a Jackson ObjectMapper instance (it can be injected instead)
private ObjectMapper mapper = new ObjectMapper();
@Override
public Object aroundReadFrom(ReaderInterceptorContext context)
throws IOException, WebApplicationException {
// Parse the request entity into the Jackson tree model
JsonNode tree = mapper.readTree(context.getInputStream());
// Extract the values you need from the tree
// Proceed to the next interceptor in the chain
return context.proceed();
}
}
我有一个过滤器,POST REST api 与之配合使用,我想在过滤器中提取我的负载的以下部分。
{
"foo": "bar",
"hello": "world"
}
过滤代码:-
public class PostContextFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext)
throws IOException {
String transactionId = requestContext.getHeaderString("id");
// Here how to get the key value corresponding to the foo.
String fooKeyVal = requestContext. ??
}
}
我没有看到任何简单的方法可以使用 ContainerRequestContext
对象将有效负载发送到 api。
所以我的问题是如何在我的有效负载中获取与 foo 键对应的键值。
虽然过滤器主要用于操纵请求和响应参数,如 HTTP headers、URI and/or HTTP 方法,但拦截器旨在通过操纵实体 input/output 流来操纵实体。
A ReaderInterceptor
允许您操纵 入站 实体流,即来自 来自 [=24] 的流=].使用 Jackson 解析入站实体流,你的拦截器可能是这样的:
@Provider
public class CustomReaderInterceptor implements ReaderInterceptor {
// Create a Jackson ObjectMapper instance (it can be injected instead)
private ObjectMapper mapper = new ObjectMapper();
@Override
public Object aroundReadFrom(ReaderInterceptorContext context)
throws IOException, WebApplicationException {
// Parse the request entity into the Jackson tree model
JsonNode tree = mapper.readTree(context.getInputStream());
// Extract the values you need from the tree
// Proceed to the next interceptor in the chain
return context.proceed();
}
}