简介
RestTemplate是执行HTTP请求的同步阻塞式的客户端,它在HTTP客户端库(例如JDK HttpURLConnection,Apache HttpComponents,okHttp等)基础上封装了更加简单易用的模板方法API。它的操作更加方便、快捷,能很大程度上提升我们的开发效率。
Spring boot 集成RestTemplate
1.pom文件下引入相关jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency
2.编写配置类
@Configuration
public class RestTemplateConfig
{
//默认使用JDK 自带的HttpURLConnection作为底层实现
@Bean
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate();
return restTemplate;
}
}
3.调用RestTemplate API接口
@RequestMapping("/test")
public class TestController
{
@Autowired
private RestTemplateConfig restTemplateConfig;
}
通过注入RestTemplateConfig就能够使用对应的API接口。