1
我想获得HttpServletResponse的返回内容以供登录自定义拦截器。开发环境是Spring Boot 1.5.6 + Java 8 + Embeded Tomcat 8.0.35,并且返回的内容是RESTful接口的json字符串。这是我的代码获取http回应内容:如何在Spring Boot中获得完整的HttpServletResponse响应体?
/**
* get Response return json content
*
* @param response
* @return
* @throws IOException
* @throws NoSuchFieldException
* @throws IllegalAccessException
*/
public String getResponseContent(HttpServletResponse response) throws IOException, NoSuchFieldException, IllegalAccessException {
String responseContent = null;
CoyoteOutputStream outputStream = (CoyoteOutputStream) response.getOutputStream();
Class<CoyoteOutputStream> coyoteOutputStreamClass = CoyoteOutputStream.class;
Field obField = coyoteOutputStreamClass.getDeclaredField("ob");
if (obField.getType().toString().endsWith("OutputBuffer")) {
obField.setAccessible(true);
org.apache.catalina.connector.OutputBuffer outputBuffer = (org.apache.catalina.connector.OutputBuffer) obField.get(outputStream);
Class<org.apache.catalina.connector.OutputBuffer> opb = org.apache.catalina.connector.OutputBuffer.class;
Field outputChunkField = opb.getDeclaredField("outputChunk");
outputChunkField.setAccessible(true);
if (outputChunkField.getType().toString().endsWith("ByteChunk")) {
ByteChunk bc = (ByteChunk) outputChunkField.get(outputBuffer);
Integer length = bc.getLength();
if (length == 0) return null;
responseContent = new String(bc.getBytes(), "UTF-8");
Integer responseLength = StringUtils.isBlank(responseContent) ? 0 : responseContent.length();
if (responseLength < length) {
responseContent = responseContent.substring(0, responseLength);
} else {
responseContent = responseContent.substring(0, length);
}
}
}
return responseContent;
}
当响应JSON是短,运行well.But当返回JSON过长的代码,只有具有响应内容的一部分,解析内容responseContent记录(需要分析之前失败json并获得一些值写入数据库)。
如何调整响应并获得完整响应内容?
您是否计算了响应大小并检查了您的tomcat响应限制 – CHiRAG
阅读此:https://stackoverflow.com/questions/33744875/spring-boot-how-to-log-all-requests-and-responses-with -exceptions输入单-PL –