Spring框架下,Http返回的Response格式为org.apache.cataline.connector.ResponseFacade, 类中没有可视化获取http返回体的方式,返回体以字节流形式存在于返回对象的outputBuffer中。
开发过程中,打断点排查问题,在Spring框架的类中打断点后,想要获取Response中可读返回内容的方式,就是将返回对象中的字节数组,写入String构造方法中,实现可读显示。
具体代码如下。
// ResponseFacade responseFacade 是Spring框架断点中获取的返回对象
// 获取内部的 Response 对象
Field responseField = ResponseFacade.class.getDeclaredField("response");
responseField.setAccessible(true);
Object response = responseField.get(responseFacade);
// 获取 Response 的 OutputBuffer
Method getOutputBufferMethod = response.getClass().getMethod("getOutputBuffer");
Object outputBuffer = getOutputBufferMethod.invoke(response);
// 获取缓冲区内容
Method getBufferMethod = outputBuffer.getClass().getMethod("getBuffer");
getBufferMethod.setAccessible(true);
byte[] buffer = (byte[]) getBufferMethod.invoke(outputBuffer);
// 获取实际使用的缓冲区大小
Method getFilledMethod = outputBuffer.getClass().getMethod("getFilledSize");
int filledSize = (int) getFilledMethod.invoke(outputBuffer);
// 转换为字符串
return new String(buffer, 0, filledSize, StandardCharsets.UTF_8);