产生的错误
java.nio.charset.MalformedInputException: Input length = 1
发生的原因
post请求接收数据时,由于对接方发送过来的数据量过大,经过nginx时,被Gzip进行数据流压缩,导致使用InputStream 流读取body数据抛出上述异常
解决方案
配置拦截器
对指定的路径进行拦截器body进行Gzip解压处理
import java.io.IOException;import java.util.Arrays;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.annotation.WebFilter;import javax.servlet.http.HttpServletRequest;import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Component;@Component@WebFilter( filterName = "GZIPFilter", urlPatterns = {"/test/**"})@Slf4jpublic class GZIPFilter implements Filter { private static final String[] gzipPath = new String[]{"/test/add"}; public GZIPFilter() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; String url = req.getRequestURI(); log.info(" url: {}", url); if (Arrays.asList(gzipPath).contains(url)) { // 对指定路径下的请求进行gzip解压 chain.doFilter(new GZIPRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } public void destroy() { }}
解压
解压gzip
import lombok.extern.slf4j.Slf4j;import java.io.IOException;import java.util.zip.GZIPInputStream;import javax.servlet.ReadListener;import javax.servlet.ServletInputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;@Slf4jpublic class GZIPRequestWrapper extends HttpServletRequestWrapper { private HttpServletRequest request; public GZIPRequestWrapper(HttpServletRequest request) { super(request); this.request = request; } public ServletInputStream getInputStream() throws IOException { ServletInputStream stream = this.request.getInputStream(); String contentEncoding = this.request.getHeader("Content-Encoding"); log.info(" contentEncoding: {}", contentEncoding); if (null != contentEncoding && contentEncoding.indexOf("gzip") != -1) { try { final GZIPInputStream gzipInputStream = new GZIPInputStream(stream); ServletInputStream newStream = new ServletInputStream() { public int read() throws IOException { return gzipInputStream.read(); } public boolean isFinished() { return false; } public boolean isReady() { return false; } public void setReadListener(ReadListener arg0) { } }; return newStream; } catch (Exception var5) { var5.printStackTrace(); } } return stream; }}
来源地址:https://blog.csdn.net/xiaomzhng/article/details/131358886