如何从 Java 异常中获取 responseBody

How to get responseBody from Java Exception

在调用 REST 服务时,它给出了 HttpClientErrorException,我能够检索状态代码和错误消息,但是我怎样才能得到 responseBody

我正在尝试下面的代码,但无法转换为 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(); 
}

我做错了什么?谁能推荐一下?

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