产生的错误 java.NIO.charset.MalfORMedInputException: Input length = 1 发生的原因 post请求接收数据时,由于对接方发送过来的数据量过大,经
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
--结束END--
本文标题: java.nio.charset.MalformedInputException: Input length = 1
本文链接: https://lsjlt.com/news/392160.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-04-01
2024-04-03
2024-04-03
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0