Spring Boot中HttpServletRequest无法获取特定设备请求体问题求助
Spring Boot控制器无法获取特定设备请求体的问题求助
问题背景
在Spring Boot项目中,使用BC TLS PSK方案与SIM卡通信时遇到异常:控制器无法获取特定设备发送的请求体。该通信方案已稳定运行多年,仅在与部分特定设备交互时出现此问题。
环境信息
- Spring Boot 2.5.15
- Java 8
- BC jdk8on 1.78.1
控制器方法
public void anyRequest(@RequestHeader(value = CONTENT_TYPE, required = false) String requestContentType, @RequestHeader(value = HEADER_X_ADMIN_PROTOCOL) String adminProtocol, @RequestHeader(value = HEADER_X_ADMIN_FROM) String adminFrom, @RequestHeader(value = HEADER_X_ADMIN_RESUME, required = false, defaultValue = "false") boolean adminResume, @RequestHeader(value = HEADER_X_ADMIN_SCRIPT_STATUS, required = false) String adminScriptStatus, @RequestBody(required = false) byte[] body, final HttpServletRequest request, final HttpServletResponse response) throws InterruptedException, IOException {
常规请求体获取方式
Long contentLength = request.getContentLengthLong(); log.info("Request Content lenght in header: {}", contentLength); if (body != null) { log.info("body content {} ", Hex.encodeHexString(body)); }
该方式在99%的场景下正常工作,但针对特定设备时body始终为null。
尝试过的替代获取方式
方式一
if (body == null && contentLength > 0) { log.warn("Body seems null while Content length Header is {} ", contentLength); log.info("Trying alternative way to retreive the body {} ", contentLength); InputStream is = request.getInputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } body = buffer.toByteArray(); }
方式二(返回全零字节数组,仍尝试过)
private byte[] alternateBodybytes(InputStream serveltInputStream, int contentLength) throws IOException { byte[] bytes = new byte[contentLength]; for (int r, offset = 0; (r = serveltInputStream.read(bytes, offset, bytes.length - offset)) > -1;) { offset += r; } return bytes; }
求助问题
- 是否有其他方法可以在Spring Boot框架的更低层级获取原始请求体?
- 希望尽量避免升级Spring/Java版本(会带来大量回归测试),但如果有必要也可以考虑,想了解是否存在版本相关的已知问题。
抓包情况说明
通过tcpdump抓包可看到请求体(如AF 80 23 11 .. .. 00 00),且Content-Length头明确表明请求体存在。对比成功场景的抓包,未发现明显差异。
内容的提问来源于stack exchange,提问作者maxime chevry
相关产品推荐
相关产品推荐

