RestTemplate
是执行HTTP请求的同步阻塞式的客户端,它在HTTP客户端库(例如JDK HttpURLConnection,Apache HttpComponents,okHttp等)基础封装了更加简单易用的模板方法API。也就是说RestTemplate是一个封装,底层的实现仍是java应用开发中经常使用的一些HTTP客户端。可是相对于直接使用底层的HTTP客户端库,它的操做更加方便、快捷,能很大程度上提高咱们的开发效率。vue
RestTemplate
做为spring-web项目的一部分,在Spring 3.0版本开始被引入。RestTemplate类经过为HTTP方法(例如GET,POST,PUT,DELETE等)提供重载的方法,提供了一种很是方便的方法访问基于HTTP的Web服务。若是你的Web服务API基于标准的RESTful风格设计,使用效果将更加的完美。java
根据Spring官方文档及源码中的介绍,RestTemplate在未来的版本中它可能会被弃用,由于他们已在Spring 5中引入了WebClient做为非阻塞式Reactive HTTP客户端。可是RestTemplate目前在Spring 社区内仍是不少项目的“重度依赖”,好比说Spring Cloud。另外,RestTemplate说白了是一个客户端API封装,和服务端相比,非阻塞Reactive 编程的需求并无那么高。
![]()
为了方便后续开发测试,首先介绍一个网站给你们。 JSONPlaceholder是一个提供免费的在线REST API的网站,咱们在开发时可使用它提供的url地址测试下网络请求以及请求参数。或者当咱们程序须要获取一些模拟数据、模拟图片时也可使用它。
RestTemplate是spring的一个rest客户端,在spring-web这个包下。这个包虽然叫作spring-web,可是它的RestTemplate能够脱离Spring 环境使用。web
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.2.6.RELEASE</version> </dependency>
测试一下Hello world,使用RestTemplate发送一个GET请求,并把请求获得的JSON数据结果打印出来。spring
@Test public void simpleTest() { RestTemplate restTemplate = new RestTemplate(); String url = "http://jsonplaceholder.typicode.com/posts/1"; String str = restTemplate.getForObject(url, String.class); System.out.println(str); }
服务端是JSONPlaceholder网站,帮咱们提供的服务端API。须要注意的是:"http://jsonplaceholder.typicode.com/posts/1"服务URL,虽然URL里面有posts这个单词,可是它的英文含义是:帖子或者公告,而不是咱们的HTTP Post协议。因此说"http://jsonplaceholder.typicode.com/posts/1",请求的数据是:id为1的Post公告资源。打印结果以下:编程
这里咱们只是演示了RestTemplate 最基础的用法,RestTemplate 会写成一个系列的文章,请你们关注。json
将maven坐标从spring-web换成spring-boot-starter-web后端
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
将RestTemplate配置初始化为一个Bean。这种初始化方法,是使用了JDK 自带的HttpURLConnection做为底层HTTP客户端实现。咱们还能够把底层实现切换为Apache HttpComponents,okHttp等,咱们后续章节会为你们介绍。springboot
@Configuration public class ContextConfig { //默认使用JDK 自带的HttpURLConnection做为底层实现 @Bean public RestTemplate restTemplate(){ RestTemplate restTemplate = new RestTemplate(); return restTemplate; } }
在须要使用RestTemplate 的位置,注入并使用便可。网络
@Resource //@AutoWired private RestTemplate restTemplate;
以为对您有帮助的话,帮我点赞、分享!您的支持是我不竭的创做动力! 。另外,笔者最近一段时间输出了以下的精品内容,期待您的关注。前后端分离