简体   繁体   中英

How to get full HttpServletResponse response body in Spring Boot?

I want to get HttpServletResponse return content for logging in custom interceptor.The develop enviroment is Spring Boot 1.5.6 + Java 8 + Embeded Tomcat 8.0.35,and return content is RESTful interface json string.This is my code to get http response content:

 /**
 * 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;
}

When response json is short, the code running well.But when the return json is too long,the responseContent only having part of the response content,parsing the content failed before logging(need to parsing json and get some value write to database).

How to adapt the response and get full response content?

Increse tomcat defult buffer size:

//default buffer size is:8*1024,in OutputBuffer class
//public static final int DEFAULT_BUFFER_SIZE = 8*1024;         
response.setBufferSize(2048 * 20);

This is not a perfect solution,when the response size beyond 2048 * 20,it will encount an exception.But could handle most response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM