我想获取HttpServletResponse返回内容以登录自定义拦截器。开发环境是Spring Boot 1.5.6 + Java 8 + Embeded Tomcat 8.0.35,返回内容是RESTful接口json string。这是我的代码获取http响应内容:
/**
* 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很短时,代码运行良好。但是当返回json太长时,responseContent只有部分响应内容,在记录之前解析内容失败(需要解析json并获取一些值写入数据库)。
如何调整响应并获得完整的响应内容?
答案 0 :(得分:0)
增加tomcat defult缓冲区大小:
//default buffer size is:8*1024,in OutputBuffer class
//public static final int DEFAULT_BUFFER_SIZE = 8*1024;
response.setBufferSize(2048 * 20);
这不是一个完美的解决方案,当响应大小超过2048 * 20时,它会引发异常。但是可以处理大多数响应。