如何在同一RestTemplate上使用自定义ResponseErrorHandler和ClientHttpRequestFactory?

时间:2019-05-14 20:07:48

标签: error-handling resttemplate

我正在使用RestTemplate并添加了一个处理程序来处理一些错误:

@Configuration
public class IntegrationConfiguration {

@Bean
public RestTemplate restTemplate() {

    return new RestTemplateBuilder()
            .errorHandler(new CustomErrorHandler())
            .setConnectTimeout(4000)
            .setReadTimeout(4000)
            .build();
}

这是CustomErrorHandler实现:

public class CustomErrorHandler implements ResponseErrorHandler {

@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
    return response.getStatusCode().is4xxClientError() || 
           response.getStatusCode().is5xxServerError();
}

@Override
public void handleError(ClientHttpResponse response) throws IOException {

    final String body = new BufferedReader(new InputStreamReader(response.getBody()))
              .lines().collect(Collectors.joining("\n"));
    // more non important code...
} 

但是我明白了

java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1692)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)

当我尝试response.getBody()时。我找到了这个answer,但是要实现它,如果这个答案只接受扩展ClientHttpRequestFactory的类,该如何设置ClientHttpRequestFactory实现(如上所示)?

ClientHttpRequestFactory是一个功能接口。

1 个答案:

答案 0 :(得分:0)

我设法使用一个以HttpRequestFactory作为参数并使用setter插入ErrorHandler的构造函数来完成此操作:

@Bean
public RestTemplate restTemplate() {
    final SimpleClientHttpRequestFactory httpRequestFactory = new SimpleClientHttpRequestFactory();
    httpRequestFactory.setOutputStreaming(false);
    httpRequestFactory.setConnectTimeout(config.getTimeOut()*1000);
    httpRequestFactory.setReadTimeout(config.getTimeOut()*1000);

    final RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
    restTemplate.setErrorHandler(new CustomErrorHandler());
    return restTemplate;
}