2017-04-24 60 views
0

在調用REST服務時,它給出HttpClientErrorException,我能夠檢索狀態碼和錯誤消息,但是如何獲得responseBody如何從Java異常獲得響應身體異常

我在嘗試波紋管代碼,但無法調整到HttpResponse

catch(HttpClientErrorException e) { 
    // I am trying to typecast to HttpResponse, but its throwing error 
    HttpResponse response = (HttpResponse) e; 
    String msg = response.getEntity().getContent().toString(); 
} 

我在做什麼錯?任何人都可以請建議?

+1

你查找的Javadoc HttpClientErrorException?你會看到它繼承了這些方法:getResponseBodyAsByteArray,getResponseBodyAsString,getResponseHeaders - 它們不適合嗎? –

回答

1

HttpClientErrorException延伸RestClientResponseException它包含方法getResponseBodyAsString()

所以這是它轉換爲HttpResponse一個錯誤,其實HttpClientErrorException不延長HttpResponse

只要做到這一點

catch(HttpClientErrorException e){ 
    String body = e.getResponseBodyAsString(); 
} 

欲瞭解更多信息http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/HttpClientErrorException.html

+0

謝謝Flood2d。 – Bharath

+0

如果您接受答案,我將不勝感激,如果有用,謝謝! – Flood2d

+1

完成,謝謝:-) – Bharath