使用RestTemplate
配置bean注入的方式
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);;
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);
factory.setConnectTimeout(5000);
return factory;
}
}
配置拦截器
实现ClientHttpRequestInterceptor
public class HttpInterceptor implements ClientHttpRequestInterceptor {
private Logger log = LoggerFactory.getLogger(HttpInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
log.info("请求地址:{}", request.getURI());
log.info("请求方法: {}", request.getMethod());
log.info("请求内容:{}", new String(body));
log.info("请求头:{}", request.getHeaders());
return execution.execute(request, body);
}
}
修改生成RestTemplate
的bean,添加拦截器
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.getInterceptors().add(new HttpInterceptor());
return restTemplate;
}
使用RestTemplate
RequestBean requestBean = new RequestBean();
requestBean.setTest1("1");
requestBean.setTest2("2");
requestBean.setTest3("3");
RestTemplate restTemplate = new RestTemplate();
ResponseBean responseBean = restTemplate.postForObject(url, requestBean, ResponseBean.class);
返回的数据中带有泛型
上面的例子是普通的类型确定的返回值,通常我们请求接口是有一个固定的返回bean,会有一个泛型的data,RestTemplate需要知道泛型的类型(在Apache-HttpClient中是接收String的json字符串,然后用json序列化工具反序列化成特定类型)。RestTemplate提供了一个ParameterizedTypeReference
可以解决这个问题。具体使用如下
ResponseEntity<RequestModel<LoginResultDTO>> responseEntity = this.restTemplate
.exchange(LOGIN_URL, HttpMethod.POST,
new HttpEntity<LoginRequestDTO>(login),
new ParameterizedTypeReference<RequestModel<LoginResultDTO>>() {
});