[英]How to get json response in Java in case of 4XX and 5XX error
I was trying out RestTemplate and Retrofit2 .我正在尝试RestTemplate和Retrofit2 。 Both the libraries throw exception in case api returns 4XX/5XX.
如果 api 返回 4XX/5XX,这两个库都会抛出异常。 The api when hit from postman gives a JSON response body, along with 4XX/5XX .
来自邮递员的 api 提供了一个 JSON 响应主体,以及 4XX/5XX 。 How can I retrieve this JSON response using RestTemplate or Retrofit2.
如何使用 RestTemplate 或 Retrofit2 检索此 JSON 响应。
Thanks.谢谢。
For that you have to create RestTemplateError handler and register that class while creating bean for RestTemplate.为此,您必须创建 RestTemplateError 处理程序并在为 RestTemplate 创建 bean 时注册该类。
@Bean
public RestTemplate getBasicRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler());
return restTemplate;
}
where your handler class has to implements ResponseErrorHandler .您的处理程序类必须实现ResponseErrorHandler 。 You can read the json response that is stored in the body .
您可以读取存储在body 中的 json 响应。
@Component
public class RestTemplateResponseErrorHandler implements ResponseErrorHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateResponseErrorHandler.class);
@Override
public boolean hasError(ClientHttpResponse httpResponse) throws IOException {
return httpResponse.getStatusCode().series() == CLIENT_ERROR
|| httpResponse.getStatusCode().series() == SERVER_ERROR;
}
@Override
public void handleError(ClientHttpResponse httpResponse) throws IOException {
if (httpResponse.getStatusCode().series() == SERVER_ERROR) {
LOGGER.error("Handling server error response statusCode:{} ", httpResponse.getStatusCode());
} else if (httpResponse.getStatusCode().series() == CLIENT_ERROR) {
LOGGER.error("Handling Client error response statusCode:{} ", httpResponse.getStatusCode());
String body;
InputStreamReader inputStreamReader = new InputStreamReader(httpResponse.getBody(),
StandardCharsets.UTF_8);
body = new BufferedReader(inputStreamReader).lines().collect(Collectors.joining("\n"));
throw new CustomException(httpResponse.getStatusCode().toString(), httpResponse, body);
}
}
}
Use the HttpClientErrorException
, HttpStatusCodeException
after try block as below.在 try 块之后使用
HttpClientErrorException
、 HttpStatusCodeException
,如下所示。
try{
restTemplate.exchange("url", HttpMethod.GET, null, String.class);
}
catch (HttpClientErrorException errorException){
logger.info("Status code :: {}, Exception message :: {} , response body ::{}" , e.getStatusCode()
e.getMessage(), e.getResponseBodyAsString());
}
catch (HttpStatusCodeException e){
logger.info("Status code :: {}, Exception message :: {} , response body ::{}" , e.getStatusCode()
e.getMessage(), e.getResponseBodyAsString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.