标签:logs str web sim client 依赖 override system status
restTemplate调用exchange方法,如果发生错误,看不到服务器返回的错误消息。或者想依赖返回的错误信息进行下一步处理。
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.nio.charset.Charset; @Configuration public class RestTemplateConfig { @Bean public RestTemplate getRestTemplate(ClientHttpRequestFactory factory) { RestTemplate restTemplate = new RestTemplate(factory); restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8"))); restTemplate.setErrorHandler(new ThrowErrorHandler()); return restTemplate; } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory() { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(10000);//单位为ms factory.setConnectTimeout(5000);//单位为ms return factory; } public class ThrowErrorHandler implements ResponseErrorHandler { @Override public boolean hasError(ClientHttpResponse response) throws IOException { //返回false表示不管response的status是多少都返回没有错 //这里可以自己定义那些status code你认为是可以抛Error return false; } @Override public void handleError(ClientHttpResponse response) throws IOException { System.out.println("================>" + response.getBody()); //这里面可以实现你自己遇到了Error进行合理的处理 } } }
SpringBoot 使用 RestTemplate 调用exchange方法 显示错误信息
标签:logs str web sim client 依赖 override system status
原文地址:https://www.cnblogs.com/liuxm2017/p/9958392.html