How to get REST api payload using ContainerRequestContext in filter method

I have a filter through which the POST REST api passes, and I want to extract the bottom of my payload into the filter.

{ "foo": "bar", "hello": "world" } 

Filter Code: -

 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. ?? } } 

I see no easy way to get the payload for api using the ContainerRequestContext object.

So my question is: how to get the key value corresponding to the foo key in my payload.

+5
source share
1 answer

While filters are mainly designed to manipulate request and response parameters, such as HTTP headers, URIs and / or HTTP methods, interceptors are designed to control objects by controlling the input / output streams of the object.

A ReaderInterceptor allows you to manipulate incoming streams of entities, that is, streams coming from wires. Using Jackson to analyze the flow of an incoming entity, your interceptor might look like this:

 @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(); } } 

This answer and this answer may also be related to your question.

+4
source

Source: https://habr.com/ru/post/1268731/


All Articles