public String getRetString(HttpServletResponse response){
try{
// 截取响应流
CoyoteOutputStream outputStream = (CoyoteOutputStream) response.getOutputStream();
Class<CoyoteOutputStream> outputStreamClass = CoyoteOutputStream.class;
Field obFiled = outputStreamClass.getDeclaredField("ob");// 取出流对象中的OutputBuffer对象,该对象记录响应到客户端的内容
obFiled.setAccessible(true);// 设置访问ob属性的权限
OutputBuffer outputBuffer = (OutputBuffer) obFiled.get(outputStream);// 取出ob
Class<OutputBuffer> outputBufferClass = OutputBuffer.class;
Field outputChunkField = outputBufferClass.getDeclaredField("outputChunk");// 取到OutputBuffer中的输出流
outputChunkField.setAccessible(true);
ByteChunk byteChunk = (ByteChunk) outputChunkField.get(outputBuffer);
Charset charset = Charset.forName("UTF-8");
byteChunk.setCharset(charset);
return byteChunk.toString();
}catch (Exception e){
return e.getMessage();
}
}
通过从HttpServletResponse 中取得输出流 然后通过反射 一步步取到输出字符集进行设置来统一输出的字符集
setAccessible(true);将私有属性设置为可访问