在做页面静态化的时候用到,就来记录以下。
SpringMVC提供 RestTemplate请求http接口,RestTemplate的底层使用第三方的http客户端工具实现http 的 请求,常用的http客户端工具有Apache HttpClient、OkHttpClient等,这里使用OkHttpClient完成http请求。
简单的说RestTemplate其实就是一个http的客户端。
使用步骤:
第一步:添加依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
第二步:配置RestTemplate
在SpringBoot启动类中配置 RestTemplate
public class ManageCmsApplication {
public static void main(String[] args) {
SpringApplication.run(ManageCmsApplication.class);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}
}
测试:
@Autowired
RestTemplate restTemplate;
@Test
public void testRestTemplate(){
ResponseEntity<Map> forEntity = restTemplate.getForEntity("http://localhost:31001/cms/config/getmodel/5a791725dd573c3574ee333f", Map.class);
Map body = forEntity.getBody();
System.out.println(body);
}
出错:
org.springframework.web.client.ResourceAccessException: I/O error on GET request for “http://localhost:31001/cms/config/getmodel/5a791725dd573c3574ee333f”: Failed to connect to localhost/0:0:0:0:0:0:0:1:31001; nested exception is java.net.ConnectException: Failed to connect to localhost/0:0:0:0:0:0:0:1:31001
Caused by: java.net.ConnectException: Failed to connect to localhost/0:0:0:0:0:0:0:1:31001
重新启动SpringBoot启动类,再启动,后解决。。。无奈。。。