如何从Java异常获取responseBody

jas*_*ssu 1 java exception httpresponse

在调用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(); 
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么 ?有人可以建议吗?

Flo*_*d2d 5

HttpClientErrorException扩展RestClientResponseException包含方法getResponseBodyAsString()

因此将其强制转换为HttpResponse,实际上HttpClientErrorException并没有扩展HttpResponse

只需这样做

catch(HttpClientErrorException e){  
     String body = e.getResponseBodyAsString();
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请访问http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/HttpClientErrorException.html