【问题标题】:How to get the payload of REST api using ContainerRequestContext in filter method如何在过滤器方法中使用 ContainerRequestContext 获取 REST api 的有效负载
【发布时间】:2017-06-10 17:32:35
【问题描述】:

我有一个过滤器,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 键对应的键值。

【问题讨论】:

    标签: java rest jersey jax-rs dropwizard


    【解决方案1】:

    过滤器主要用于操纵请求和响应参数,例如 HTTP 标头、URI 和/或 HTTP 方法,而拦截器旨在通过操纵实体输入/输出流来操纵实体。

    ReaderInterceptor 允许您操纵入站 实体流,即来自“线”的流。使用 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();
        }
    }
    

    这个answer和这个answer也可能与你的问题有关。

    【讨论】:

      猜你喜欢
      • 2015-04-26
      • 1970-01-01
      • 2019-04-23
      • 2018-03-14
      • 2017-05-26
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      • 1970-01-01
      相关资源
      最近更新 更多