java - 如何在 Spring Boot 中获取完整的 HttpServletResponse 响应主体?

标签 java spring

我想获取HttpServletResponse返回内容,用于登录自定义拦截器。开发环境为Spring Boot 1.5.6 + Java 8 + Embeded Tomcat 8.0.35,返回内容为RESTful接口(interface)json字符串。这是我获取的代码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;
}

当response json很短时,代码运行良好。但是当返回json太长时,responseContent只有部分响应内容,在记录之前解析内容失败(需要解析json并获取一些值写入数据库)。

如何适配响应并获取完整的响应内容?

最佳答案

增加 tomcat 默认缓冲区大小:

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

这不是一个完美的解决方案,当响应大小超过 2048 * 20 时,它会遇到异常。但可以处理大多数响应。

关于java - 如何在 Spring Boot 中获取完整的 HttpServletResponse 响应主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46011959/

相关文章:

Spring 数据 JPA。 Repositories 继承,抛出 BeanCreationException,NullPointerException

java - 使用JSP注释时编译错误?

java - 如何从另一个类更新JLabel的?

java - xPage ManagedBean ODA 应用程序错误

java - @Configuration 类中 @PostConstruct 的预期行为是什么?

hibernate - JSR-303 依赖注入(inject)和 Hibernate

Java 8 Streams - 为什么我不能对整数流求和?

java - eclipse JDT : Call 'correct indentation' programmatically?

java - 必须设置 Spring Security UserDetailsS​​ervice 错误

java - Groovy - 集成测试