如何从Java Exception获取responseBody

时间:2017-04-24 01:53:48

标签: 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(); 
}

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

1 个答案:

答案 0 :(得分:4)

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

相关问题