一、什么是 RestTemplate?

RestTemplate是执行HTTP申请的同步阻塞式的客户端,它在HTTP客户端库(例如JDK HttpURLConnection,Apache HttpComponents,okHttp等)根底封装了更加简略易用的模板办法API。也就是说RestTemplate是一个封装,底层的实现还是java利用开发中罕用的一些HTTP客户端。然而绝对于间接应用底层的HTTP客户端库,它的操作更加不便、快捷,能很大水平上晋升咱们的开发效率。

RestTemplate作为spring-web我的项目的一部分,在Spring 3.0版本开始被引入。RestTemplate类通过为HTTP办法(例如GET,POST,PUT,DELETE等)提供重载的办法,提供了一种十分不便的办法拜访基于HTTP的Web服务。如果你的Web服务API基于规范的RESTful格调设计,应用成果将更加的完满。

依据Spring官网文档及源码中的介绍,RestTemplate在未来的版本中它可能会被弃用,因为他们已在Spring 5中引入了WebClient作为非阻塞式Reactive HTTP客户端。然而RestTemplate目前在Spring 社区内还是很多我的项目的“重度依赖”,比如说Spring Cloud。另外,RestTemplate说白了是一个客户端API封装,和服务端相比,非阻塞Reactive 编程的需要并没有那么高。

二、非Spring环境下应用RestTemplate

为了不便后续开发测试,首先介绍一个网站给大家。JSONPlaceholder是一个提供收费的在线REST API的网站,咱们在开发时能够应用它提供的url地址测试下网络申请以及申请参数。或者当咱们程序须要获取一些模仿数据、模仿图片时也能够应用它。

RestTemplate是spring的一个rest客户端,在spring-web这个包下。这个包尽管叫做spring-web,然而它的RestTemplate能够脱离Spring 环境应用。

<dependency>  <groupId>org.springframework</groupId>  <artifactId>spring-web</artifactId>  <version>5.2.6.RELEASE</version></dependency>

测试一下Hello world,应用RestTemplate发送一个GET申请,并把申请失去的JSON数据后果打印进去。

@Testpublic 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 会写成一个系列的文章,请大家关注。

三、Spring环境下应用RestTemplate

将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等,咱们后续章节会为大家介绍。

@Configurationpublic class ContextConfig {    //默认应用JDK 自带的HttpURLConnection作为底层实现    @Bean    public RestTemplate restTemplate(){        RestTemplate restTemplate = new RestTemplate();        return restTemplate;    }}

在须要应用RestTemplate 的地位,注入并应用即可。

  @Resource //@AutoWired  private RestTemplate restTemplate;

欢送关注我的博客,外面有很多精品合集

  • 本文转载注明出处(必须带连贯,不能只转文字):字母哥博客。

感觉对您有帮忙的话,帮我点赞、分享!您的反对是我不竭的创作能源! 。另外,笔者最近一段时间输入了如下的精品内容,期待您的关注。

  • 《手摸手教你学Spring Boot2.0》
  • 《Spring Security-JWT-OAuth2一本通》
  • 《实战前后端拆散RBAC权限管理系统》
  • 《实战SpringCloud微服务从青铜到王者》
  • 《VUE深入浅出系列》