2017-09-02 43 views
1

我想獲得HttpServletResponse的返回內容以供登錄自定義攔截器。開發環境是Spring Boot 1.5.6 + Java 8 + Embeded Tomcat 8.0.35,並且返回的內容是RESTful接口的json字符串。這是我的代碼獲取http迴應內容:如何在Spring Boot中獲得完整的HttpServletResponse響應體?

/** 
* 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是短,運行well.But當返回JSON過長的代碼,只有具有響應內容的一部分,解析內容responseContent記錄(需要分析之前失敗json並獲得一些值寫入數據庫)。

如何調整響應並獲得完整響應內容?

+0

您是否計算了響應大小並檢查了您的tomcat響應限制 – CHiRAG

+1

閱讀此:https://stackoverflow.com/questions/33744875/spring-boot-how-to-log-all-requests-and-responses-with -exceptions輸入單-PL –

回答

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,它將encount的exception.But可以處理大多數的迴應。

相關問題