RestTemplate的配置和使用
配置
/**
* resttemplate 配置
*/
@Configuration
public class RestTemplateConfig {
@Bean
public SimpleClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory facotry = new SimpleClientHttpRequestFactory();
/*10s*/
facotry.setReadTimeout(10000);
/*30s*/
facotry.setConnectTimeout(30000);
return facotry;
}
@Bean(name = "restTemplate")
public RestTemplate restTemplate(SimpleClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.setErrorHandler(new RestTemplateErrorHandler());
return restTemplate;
}
}
配置异常处理
/**
* 定义处理resttemplate的异常
*/
public class RestTemplateErrorHandler implements ResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
boolean hasError = false;
int rawStatusCode = response.getRawStatusCode();
if (rawStatusCode != 200){
hasError = true;
}
return hasError;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
String body = IOUtils.toString(response.getBody(), "UTF-8");
String msg = null;
if(StringUtils.isNotEmpty(body)) {
JSONObject jsonObj = JSON.parseObject(body);
Object msgObj = jsonObj.get("errMsg");
if(msgObj == null) {
msg = body;
} else {
msg = msgObj.toString();
}
}
RestCustomException ex = new RestCustomException(response.getStatusCode(), body, (msg == null ? "" : msg));
throw ex;
}
}
抛出异常配置
public class RestCustomException extends RuntimeException {
private static final long serialVersionUID = 1L;
private HttpStatus statusCode;
private String body;
public RestCustomException(String msg) {
super(msg);
}
public RestCustomException(HttpStatus statusCode, String body, String msg) {
super(msg);
this.statusCode = statusCode;
this.body = body;
}
public HttpStatus getStatusCode() {
return statusCode;
}
public void setStatusCode(HttpStatus statusCode) {
this.statusCode = statusCode;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
还没有评论,来说两句吧...