Spring RestTemplate обрабатывает исключения - PullRequest
0 голосов
/ 07 января 2019

Я использую Spring RestTemplate для выполнения HTTP-запросов

Это мой код:

public static ResponseEntity<String> makeRequest() {
    ResponseEntity<String> response = null;
    try {
         RestTemplate restTemplate = new RestTemplate();
         response = restTemplate.exchange(URI, HttpMethod.GET, null, 
         String.class);

     }catch (HttpStatusCodeException e) {
         System.out.println(e.getStatusCode());
     }catch (Exception e) {
         e.printStackTrace();
     }
         return response;
}

В случае ответа 400 от сервера я получаю исключение, и мой метод возвращает нулевое значение.

Есть ли способ заставить Spring RestTemplate обрабатывать 400 HTTP-код как 200?

1 Ответ

0 голосов
/ 07 января 2019

Для обработки ошибок в одном месте. Также включены импортные выписки

import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

RestTemplate restTemplate() {
    SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
    clientHttpRequestFactory.setConnectTimeout(2000);
    clientHttpRequestFactory.setReadTimeout(3000);
    RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
        @Override public boolean hasError(ClientHttpResponse response)
                throws IOException {
            try {
                //Do your stuff
                return super.hasError(response);
            } catch (Exception e) {
                logger.error("Exception [" + e.getMessage() + "] occurred while trying to send the request", e);
                return true;
            }
        }

        @Override public void handleError(ClientHttpResponse response)
                throws IOException {
            try {
                //Do your stuff
                super.handleError(response);
            } catch (Exception e) {
                logger.error("Exception [" + e.getMessage() + "] occurred while trying to send the request", e);
                throw e;
            }
        }
    });



    return restTemplate;
}
...