zuul请求request中body请求体参数不能读取两次问题记录

大老板 8月前 ⋅ 526 阅读

问题

request中body参数数据读取

BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String inputStr;
while ((inputStr = reader.readLine()) != null) {
    sb.append(inputStr);
}
JSONObject jsonObject = JSONObject.parseObject(sb.toString());

request.getInputStream()读取过一次后就null了

解决

重写request

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;

/**
 * @author baojie 2021/10/18
 */
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private byte[] body;
    public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        try {
            body = StreamUtils.getByteByStream(request.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public BufferedReader getReader()  {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream()  {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read()  {
                return bais.read();
            }
        };
    }
}
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * @author baojie 2021/10/18
 */
public class StreamUtils {
    public static byte[] getByteByStream(InputStream is) throws Exception {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = is.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.flush();
        return bos.toByteArray();
    }
}

再通过前置过滤器替换掉request

@Override
public Object run() throws {
    RequestContext requestContext = RequestContext.getCurrentContext();
    requestContext.setRequest(new BodyReaderHttpServletRequestWrapper(requestContext.getRequest()));
    ....
}

全部评论: 0

    我有话说: