`

jersey获取inputstream body为空问题

    博客分类:
  • java
阅读更多

在处理一个第三方加密回调时,需要读取body的byte内容,用了springMVC后,字节数不对,后因大部分API使用jersey, 故决定用jersey, 但jersey中想要获取request的body时遇到一直无法获取的问题


取body的多种方式

 

@Post //直接注入body(也可以是String)
public void doSomething(byte[] body)
@Post  //直接注入inputStream后读取
public void doSomething(InputStream inputStream)
@Post  //从request读inputStream再读取
public void doSomething(@Context HttpServletRequest request)

 

 

结果试了各种方式,要么读不到,要么报下面这些错。。。

Only resource methods using @FormParam will work as expected

getInputStream() has already been called for this request

The resource configuration is not modifiable in this context. 

 

跟据经验InputStream只能被取一次,在配置对的情况下,还取不到大概都是这个问题,且报错也有该提示,然后主要方向就是这个了,推测是某个filter先用了inputStream,一看Springboot 自动注入了8个。。。表示想一个个找会很痛苦了

 

最后找到了stackoverflow的一个类似问题,试了下,成功了,特记录一下

https://stackoverflow.com/questions/40871054/inputstream-giving-null-data-in-messagebodyreader-jersey

 

上面的不能直接用,提供下我写的:

@Configuration
public class FilterConfig  {
    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
        return new MyHiddenHttpMethodFilter();
    }

    class MyHiddenHttpMethodFilter extends HiddenHttpMethodFilter {
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                        FilterChain filterChain) throws ServletException, IOException {
            if ("POST".equals(request.getMethod())
                    && MediaType.APPLICATION_FORM_URLENCODED.equals(request.getContentType())){
                //Skip this filter and call the next filter in the chain.
                filterChain.doFilter(request, response);
            } else {
                //Continue with processing this filter.
                super.doFilterInternal(request, response, filterChain);
            }
        }
    }
}

 

配置好后直接就可以各种花式读到body了。。。酷

后记:好奇为什么springboot会配这样一个HiddenHttpMethodFilter

查了下,原来是为了将form表单扩展,使之支持DELETE PUT。

说是在这个filter里将原始POST替换为form表单中的对应的,再传到后面处理。

具体没看了

 

 

个人博客地址:http://lnxts.com/issue/jersey-body-null.html

 

 

 

2
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics