好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

RestTemplate在Spring或非Spring环境下使用精讲

一、什么是 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 环境使用。

?

1

2

3

4

5

< dependency >

   < groupId >org.springframework</ groupId >

   < artifactId >spring-web</ artifactId >

   < version >5.2.6.RELEASE</ version >

</ dependency >

测试一下Hello world,使用RestTemplate发送一个GET请求,并把请求得到的JSON数据结果打印出来。

?

1

2

3

4

5

6

7

8

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

三、Spring环境下使用RestTemplate

将maven坐标从spring-web换成spring-boot-starter-web

?

1

2

3

4

< dependency >

     < groupId >org.springframework.boot</ groupId >

     < artifactId >spring-boot-starter-web</ artifactId >

</ dependency >

将RestTemplate配置初始化为一个Bean。这种初始化方法,是使用了JDK 自带的HttpURLConnection作为底层HTTP客户端实现。我们还可以把底层实现切换为Apache HttpComponents,okHttp等,我们后续章节会为大家介绍。

?

1

2

3

4

5

6

7

8

9

@Configuration

public class ContextConfig {

     //默认使用JDK 自带的HttpURLConnection作为底层实现

     @Bean

     public RestTemplate restTemplate(){

         RestTemplate restTemplate = new RestTemplate();

         return restTemplate;

     }

}

在需要使用RestTemplate 的位置,注入并使用即可。

?

1

2

@Resource //@AutoWired

private RestTemplate restTemplate;

以上就是RestTemplate在Spring或非Spring环境下使用精讲的详细内容,更多关于RestTemplate在Spring环境下中使用的资料请关注其它相关文章!

原文链接:https://zimug.blog.csdn.net/article/details/107705070

查看更多关于RestTemplate在Spring或非Spring环境下使用精讲的详细内容...

  阅读:24次