概述:
spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接, 我们只需要传入url及返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。
用法:
官方api文档:
RestTemplate (Spring Framework 5.3.10 API)
GET 请求
在 RestTemplate 中,和 GET 请求相关的方法有两类:getForEntity 和 getForObject,这里只介绍getForEntity
getForObject 和 getForEntity 的区别
getForObject函数实际上是对getForEntity函数的进一步封装,如果你只关注返回的消息体的内容,对其他信息都不关注,此时可以使用getForObject。
ResponseEntity<T>
是Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等。如果需要提取其中的部分属性的话直接从ResponseEntity中调用相应的方法即可
getForEntity
// RestTemplate发送get请求---不携带任何参数
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> res = restTemplate.getForEntity("http://localhost:8080/user/{id}", String.class);
// 当String类型的url地址中有参数的位置,可以理解为占位符
RestTemplate restTemplate = new RestTemplate();
2 ResponseEntity<String> res = restTemplate.getForEntity("http://localhost:8080/user/{id}", String.class, "1");
// 将参数封装到map集合中传递
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", 11);
ResponseEntity<String> res = restTemplate.getForEntity(
"http://localhost::8080/user/{id}", String.class, map);
String body = res.getBody();//返回的ResponseEntity中包含了头信息,body信息,状态码等信息。
Post请求
postForEntity
1.方法的第一参数表示要调用的服务的地址
2.方法的第二个参数表示上传的参数
3.方法的第三个参数表示返回的消息体的数据类型
Book book = new Book();
book.setName("红楼梦");
ResponseEntity<Book> responseEntity = restTemplate.postForEntity("http://HELLO-SERVICE/getbook2", book, Book.class);
responseEntity.getBody().getName();