2017-05-03 73 views
0

我正在嘗試使用HttpServletResponse.getOutputStream()HttpServletResponse.setStatus(int)來編寫自定義響應。彈簧控制器,通過HttpServletResponse的自定義響應

但是,與地位不同的任何事情都不會考慮我寫的響應主體。

我有2個Web應用程序運行在不同的端口上,應用程序「A」必須從應用程序「B」請求數據。爲此,我創建了一個控制器來將應用程序「A」上的所有請求傳送到應用程序「B」。

例子:

@RequestMapping("/tunnel/**") 
public void exchange(HttpServletRequest request, HttpServletResponse response) throws IOException { 
    // my service tunnel the request to another server 
    // and the response of the server must be replied 

    ResponseDescriptor tunnelResponse = tunnelService.request(request); 

    response.setStatus(tunnelResponse.getStatus()); 
    // if the status was different them 200, the next line will not work 
    response.getOutputStream().write(tunnelResponse.getResponseBodyAsByteArray()); 
} 

注意,我需要從應用程序的響應是來自應用程序B.

回答

0

解決!

我創建了一個@ExceptionHandler和一個自定義異常TunnelException extends RuntimeException

所以,在我的exchange(...)方法,我抓住RestClientResponseException,並把我自己的異常封裝(在異常)的HeadersHttpStatusResponseBody byte array

這是異常處理程序:

@ExceptionHandler(TunnelException.class) 
public ResponseEntity<?> handleTunnelException(TunnelException ex) throws IOException { 
    return ResponseEntity 
      .status(ex.getStatus()) 
      .contentType(ex.getHeaders().getContentType()) 
      .body(ex.getBody()); 
} 
0

你需要捕捉HttpStatusCodeException讓其他反應比200

的確切回覆
try { 
    ResponseDescriptor tunnelResponse = tunnelService.request(request); 
    response.setStatus(tunnelResponse.getStatus()); 
    response.getOutputStream().write(tunnelResponse.getResponseBodyAsByteArray()); 
} catch (HttpStatusCodeException e) { 
    response.setStatus(e.getStatusCode().value()); 
    response.getOutputStream().write(e.getResponseBodyAsByteArray()); 
} 
+0

我已經這樣做了。我發現了這個異常,並且也在ResponseDescriptor中返回了響應異常信息。 –

+0

你使用spring restTemplate來調用它嗎?你能分享這段代碼嗎? – mhshimul

+0

此解決方案不起作用。狀態碼返回,但是主體總是空的。 –