custom error handler: rest template default will throw xxException if response status is bot 200
@Component
public class RestTemplateErrorHandle extends DefaultResponseErrorHandler {
@Override
public void handleError(ClientHttpResponse response) {}
}
if response is not json, rest template will throw RestClientException
// TODO: so need overwrite ResponseExtractor to get response firstly, but there are issue about InputStream read repeated.
RestTemplateProxy
@Component
public class RestTemplateProxy extends RestTemplate {
@Override
public <T> ResponseExtractor<ResponseEntity<T>> responseEntityExtractor(Type responseType) {
return new NoExceptionRestTemplateResponseEntityExtractor<>(
responseType, getMessageConverters());
}
}
NoExceptionRestTemplateResponseEntityExtractor
public class NoExceptionRestTemplateResponseEntityExtractor<T>
implements ResponseExtractor<ResponseEntity<T>> {
private static final Logger log =
LoggerFactory.getLogger(NoExceptionRestTemplateResponseEntityExtractor.class);
private final HttpMessageConverterExtractor<T> delegate;
NoExceptionRestTemplateResponseEntityExtractor(
Type responseType, List<HttpMessageConverter<?>> converters) {
if (responseType != null && Void.class != responseType) {
this.delegate = new HttpMessageConverterExtractor<>(responseType, converters);
} else {
this.delegate = null;
}
}
@Override
public ResponseEntity<T> extractData(ClientHttpResponse response) throws IOException {
if (this.delegate != null) {
T body = null;
try {
// TODO: read response firstly, then call super method
/*
InputStream inputStream = response.getBody();
BufferedInputStream buffInputStream = new BufferedInputStream(inputStream);
buffInputStream.mark(inputStream.available() + 1);
String content = new String(ByteStreams.toByteArray(buffInputStream), Charsets.UTF_8);
buffInputStream.reset();
*/
body = this.delegate.extractData(response);
} catch (RuntimeException e) {
return new ResponseEntity(null, response.getHeaders(), response.getStatusCode());
}
return new ResponseEntity<>(body, response.getHeaders(), response.getStatusCode());
} else {
return new ResponseEntity<>(response.getHeaders(), response.getStatusCode());
}
}
}
usage
// TODO: so need overwrite
ResponseExtractor
to get response firstly, but there are issue about InputStream read repeated.