上篇博客中,简单介绍了RestTemplate,只是用到了单元测试环节,如果在正式开发环境使用RestTemplate调用远程接口,还有一些配置要做。
一、配置类
由于Spring boot没有对RestTemplate做自动配置,所以我们需要写一个配置类引入RestTemplate。
@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);//单位为ms factory.setConnectTimeout(5000);//单位为ms return factory; } }
二、工具类
在实际开发过程中,可能对于调用远程接口有多种参数情况,因此写了一个工具类用来支持。
RestTemplate功能非常强大,Post请求的时候特别要注意,body参数必须为MultiValueMap类型。
@Service public class RestTemplateService { @Autowired private RestTemplate restTemplate; /** * 实测可用 */ public JSONObject doGet(String url) { JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody(); return json; } /** * 实测可用 */ public JSONObject doGet(String url, HttpHeaders headers) { HttpEntity<String> entity = new HttpEntity<>(null, headers); ResponseEntity<JSONObject> exchange = restTemplate.exchange(url, HttpMethod.GET, entity, JSONObject.class); return exchange.getBody(); } /** * 实测可用,body参数必须为MultiValueMap类型 */ public JSONObject doPost(String url, MultiValueMap<String, Object> param) { JSONObject json = restTemplate.postForEntity(url, param, JSONObject.class).getBody(); return json; } /** * 实测可用,body参数必须为MultiValueMap类型 */ public JSONObject doPost(String url, MultiValueMap<String, Object> params, HttpHeaders headers) { JSONObject json = restTemplate.postForObject(url, new HttpEntity<>(params, headers), JSONObject.class); return json; } }