简体   繁体   English

4XX 和 5XX 错误时如何在 Java 中获取 json 响应

[英]How to get json response in Java in case of 4XX and 5XX error

I was trying out RestTemplate and Retrofit2 .我正在尝试RestTemplateRetrofit2 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 块之后使用HttpClientErrorExceptionHttpStatusCodeException ,如下所示。

    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.

相关问题 Spring WebClient - 如何在出现 HTTP 错误(4xx、5xx)的情况下访问响应正文? - Spring WebClient - how to access response body in case of HTTP errors (4xx, 5xx)? 如何使用4xx / 5xx状态代码,Java servlet / HttpURLConnection处理HTTP响应 - How to handle HTTP response with a 4xx/5xx status code, Java servlet/HttpURLConnection JerseyClient不会为4xx和5xx响应抛出异常 - JerseyClient not throwing exception for 4xx and 5xx response Java Spring Boot 框架 - WebClient 记录 4xx/5xx 主体响应 - Java Spring Boot framework - WebClient logging 4xx/5xx body response 有没有办法模拟HTTP错误响应5xx和4xx - Is there any way to simulate HTTP Error responses 5xx and 4xx 解析 try catch 块中的异常以分配响应代码 - 2xx、4xx 或 5xx - Parse exception in try catch block to assign a response code - 2xx, 4xx or 5xx 防止Tomcat在HTTP错误状态4xx或5xx上干扰Jersey / JAX-RS 2响应主体 - Prevent Tomcat from interfering with Jersey/JAX-RS 2 Response Body on HTTP Error Status 4xx or 5xx 如何处理骆驼中的4xx(不重试)和5xx(重试)异常 - How to handle 4xx(without retry) and 5xx (with retry) exceptions in camel 有没有办法用 Mockito 测试所有 5XX 或 4XX 代码? - is there a way to test all 5XX or 4XX codes with Mockito? 春季启动-记录每4xx和5xx包括请求 - Spring boot - Log every 4xx and 5xx including the request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM