HttpServletRequestWrapper改写http请求body
package cn.xs.qishi.open.api.filter; import cn.xs.ambi.bas.util.StringUtils; 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.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.*; /** * @author liuxn * @date 2022/5/24 */ public class RequestWrapper extends HttpServletRequestWrapper { private Map<String, String> headerMap = new HashMap<>(); // 重新赋值的body数据 private String body; public RequestWrapper(HttpServletRequest request) { super(request); } public void addHeader(String name, String value) { headerMap.put(name, value); } public void setBody(String body) { this.body = body; } @Override public int getContentLength() { return this.body.getBytes(StandardCharsets.UTF_8).length; } @Override public long getContentLengthLong() { return this.body.getBytes(StandardCharsets.UTF_8).length; } @Override public ServletInputStream getInputStream() throws IOException { if (StringUtils.isBlank(body)) { body = ""; } // 必须指定utf-8编码,否则json请求数据中如果包含中文,会出现异常 final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)); 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() throws IOException { return byteArrayInputStream.read(); } }; } @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(this.getInputStream())); } @Override public String getHeader(String name) { String headerValue = super.getHeader(name); if (headerMap.containsKey(name)) { headerValue = headerMap.get(name); } return headerValue; } @Override public Enumeration<String> getHeaderNames() { List<String> names = Collections.list(super.getHeaderNames()); names.addAll(headerMap.keySet()); return Collections.enumeration(names); } @Override public Enumeration<String> getHeaders(String name) { List<String> values = Collections.list(super.getHeaders(name)); if (headerMap.containsKey(name)) { values.add(headerMap.get(name)); } return Collections.enumeration(values); } }
问题记录:- Content-length different from byte array length! cl=97, array=117
问题点:getContentLength()、getContentLengthLong()这两个方法取值不正确
正确写法:
@Override public int getContentLength() { return this.body.getBytes(StandardCharsets.UTF_8).length; } @Override public long getContentLengthLong() { return this.body.getBytes(StandardCharsets.UTF_8).length; }