产生的错误
java.nio.charset.MalformedInputException: Input length = 1
发生的原因
post请求接收数据时,由于对接方发送过来的数据量过大,经过nginx时,被Gzip进行数据流压缩,导致使用InputStream 流读取body数据抛出上述异常
解决方案
配置拦截器
对指定的路径进行拦截器body进行Gzip解压处理文章来源:https://www.toymoban.com/news/detail-687289.html
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/**"}
)
@Slf4j
public 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文章来源地址https://www.toymoban.com/news/detail-687289.html
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;
@Slf4j
public 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;
}
}
到了这里,关于java.nio.charset.MalformedInputException: Input length = 1的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!