ZuulFilter HttpServletRequestWrapper form-data接受参数为空

springCloud | 2021-12-22 10:00:52

1.问题

大部分接口都是application/json类型传参 @RequestBody接受参数,有个别接口时form-data传参,普通dto接受参数,但这种情况就是接受不到参数,request.getParameterMap()也是空得

2.原因

网上查了一下是request.getParameterMap()和getInputStream()是互斥的,都是通过流读取数据,读了一次就没有了

我的ZuulFilter参数封装的代码:

       return new HttpServletRequestWrapper(request) {
            @Override
            public BufferedReader getReader() throws IOException {
                return new BufferedReader(new InputStreamReader(getInputStream()));
            }

            @Override
            public ServletInputStream getInputStream() throws IOException {
                return new ServletInputStreamWrapper(reqBodyBytes);
            }

            @Override
            public int getContentLength() {
                return reqBodyBytes.length;
            }

            @Override
            public long getContentLengthLong() {
                return reqBodyBytes.length;
            }

        };

 

我改成 return new HttpServletRequestWrapper(request);form-data就能正常传递

3.解决

根据参数类型判断


        if(request.getContentType().toLowerCase().contains(MediaType.MULTIPART_FORM_DATA_VALUE)){
            return new HttpServletRequestWrapper(request);
        }

        return new HttpServletRequestWrapper(request) {
            @Override
            public BufferedReader getReader() throws IOException {
                return new BufferedReader(new InputStreamReader(getInputStream()));
            }

            @Override
            public ServletInputStream getInputStream() throws IOException {
                return new ServletInputStreamWrapper(reqBodyBytes);
            }

            @Override
            public int getContentLength() {
                return reqBodyBytes.length;
            }

            @Override
            public long getContentLengthLong() {
                return reqBodyBytes.length;
            }
        };

 

 

登录后即可回复 登录 | 注册
    
关注编程学问公众号