RestTemplate是SpringMvc提供的请求http接口,可以使用第三方的http客户端工具完成http请求,比如HttpClient、OkHttpClient等客户端工具,本例使用OkHttpClient完成http请求
- pom.xml中添加依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
- 将RestTemplate注入到Spring容器中,指定客户端为OkHttpClient
@Bean
public RestTemplate restTemplate(){
//创建请求模板类,使用OkHttpClient完成http请求
return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}
- 测试代码:
@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {
@Autowired
private RestTemplate restTemplate;
/**
* 测试RestTemplate请求模板的get请求的使用
*/
@Test
public void testRestTemplate() {
//调用RestTemplate的get请求方法获取返回实体,指定返回类型为Map类型
ResponseEntity<Map> forEntity = restTemplate.getForEntity("http://localhost:31001/cms/config/getModel/5a791725dd573c3574ee333f", Map.class);
//获取返回实体中的数据
Map body = forEntity.getBody();
System.out.println(body);
}
}