Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从Java异常获取responseBody_Java_Exception_Httpresponse - Fatal编程技术网

如何从Java异常获取responseBody

如何从Java异常获取responseBody,java,exception,httpresponse,Java,Exception,Httpresponse,调用REST服务时,它给出了HttpClientErrorException,我能够检索状态代码和错误消息,但是如何获取响应库 我正在尝试下面的代码,但无法键入到HttpResponse catch(HttpClientErrorException e) { // I am trying to typecast to HttpResponse, but its throwing error HttpResponse response = (HttpResponse) e;

调用REST服务时,它给出了
HttpClientErrorException
,我能够检索状态代码和错误消息,但是如何获取
响应库

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

有关更多信息

您是否查阅了javadocs中的HttpClientErrorException?您将看到它继承了这些方法
getResponseBodyAsByteArray、getresponsebodyastring、getResponseHeaders
-它们不合适吗?谢谢。如果您接受答案,我将不胜感激,如果有用,谢谢!