学习传送门:RestTemplate精讲
public class HttpUtils {
@Autowired
private RestTemplate restTemplate;
public <T> ResponseEntity<T> post(String uri, HttpHeaders httpHeaders, Object content, Class<T> resClass){
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
RequestEntity requestEntity = null;
try{
requestEntity = new RequestEntity<>(
content,
httpHeaders,
HttpMethod.POST,
new URI(uri));
}catch (URISyntaxException e){
e.printStackTrace();
}
return restTemplate.exchange(requestEntity, resClass);
}
public <T> ResponseEntity<T> get(String uri, HttpHeaders httpHeaders, Class<T> resClass){
HttpEntity entity = new HttpEntity(httpHeaders);
return restTemplate.exchange(uri, HttpMethod.GET, entity, resClass);
}
}
异常的处理补充:
- ResponseErrorHandler
- DefaultResponseErrorHandler
- ExtractingResponseErrorHandler
- NoOpResponseErrorHandler
- 自定义异常处理器
我们自定义异常器除了实现ResponseErrorHandler接口,还能继承DefaultResponseErrorHandler类,如果只需要自定义状态码错误检测,重写其实现的hasError方法;
boolean hasError(ClientHttpResponse response)
如果只需要自定义异常处理,重写其handleError方法即可,
void handleError(ClientHttpResponse response)
如果全部要自定义,那还是实现其ResponseErrorHandler接口好点吧!