restTemplate的使用

怼烎@ 2024-04-01 17:19 143阅读 0赞

#

目录

目录

一、概述?

二、使用步骤

1.引入依赖

2.创建RestTemplate对象,交由spring容器进行管理

3.使用方法

3.1 GET请求

3.2 POST请求

4 exchange

总结


一、概述?

RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。

二、使用步骤

1.引入依赖``

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>

2.创建RestTemplate对象,交由spring容器进行管理

列举常见的创建方式

1.启动类中注入RestTemplate对象

  1. package com.example.demo;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.web.client.RestTemplate;
  6. @SpringBootApplication
  7. public class DemoApplication {
  8. @Bean
  9. public RestTemplate getRestTemplate(){
  10. return new RestTemplate();
  11. }
  12. public static void main(String[] args) {
  13. SpringApplication.run(DemoApplication.class, args);
  14. }
  15. }

2.创建配置类,注入RestTemplate的对象

  1. package com.czxy.ssm.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.client.RestTemplate;
  5. /**
  6. * RestTemplate工具类,主要用来提供RestTemplate对象
  7. */
  8. @Configuration//加上这个注解作用,可以被Spring扫描
  9. public class RestTemplateConfig {
  10. /**
  11. * 创建RestTemplate对象,将RestTemplate对象的生命周期的管理交给Spring
  12. */
  13. @Bean
  14. public RestTemplate restTemplate(){
  15. return new RestTemplate();
  16. }
  17. }

3.创建配置类,注入RestTemplate的对象,并设置连接和请求的时间

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.http.client.ClientHttpRequestFactory;
  4. import org.springframework.http.client.SimpleClientHttpRequestFactory;
  5. import org.springframework.web.client.RestTemplate;
  6. /**
  7. * RestTemplate工具类,主要用来提供RestTemplate对象
  8. */
  9. @Configuration//加上这个注解作用,可以被Spring扫描
  10. public class RestTemplateConfig {
  11. @Bean
  12. public RestTemplate restTemplate(ClientHttpRequestFactory factory){
  13. return new RestTemplate(factory);
  14. }
  15. @Bean
  16. public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
  17. SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
  18. factory.setReadTimeout(500000);//单位为ms
  19. factory.setConnectTimeout(500000);//单位为ms
  20. return factory;
  21. }
  22. }

3.使用方法

3.1 GET请求

3.1.1 getForEntity(String url, Class responseType, Object… uriVariables)
解析: url为请求地址,responseType为请求响应体body的包装类型,uriVariables为url中的参数绑定。uriVariables是一个数组,所以他的顺序会对应url中占位符定义的数字的顺序

请求接口:

  1. @Slf4j
  2. @RestController
  3. @RequestMapping("/memo")
  4. public class BmsBillMemoController {
  5. @Autowired
  6. private IBmsBillMemoService bmsBillMemoService;
  7. /**
  8. * 获取结算账单手账详细信息
  9. */
  10. @GetMapping(value = "/{id}/{name}")
  11. public AjaxResult getInfo(@PathVariable("id") Long id,@PathVariable("name") String name) {
  12. return AjaxResult.success(bmsBillMemoService.selectBmsBillMemoById(id));
  13. }

请求代码

  1. @Test
  2. public void Rest() {
  3. String url = "http://localhost:8080/memo/{1}/{2}";
  4. Class responseType = String.class;
  5. String [] str = new String[2];
  6. str[0] = "3";
  7. str[1] = "小林";
  8. ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, responseType, str);
  9. System.out.println("1 "+responseEntity.getStatusCode());
  10. System.out.println("2 "+responseEntity.getStatusCodeValue());
  11. System.out.println("3 "+responseEntity.getHeaders());
  12. System.out.println("4 "+responseEntity.getBody());
  13. String body = responseEntity.getBody();
  14. AjaxResult ajaxResult = JSONUtil.toBean(body, AjaxResult.class);
  15. Object data = ajaxResult.get("data");
  16. BmsBillMemo bmsBillMemo = JSONUtil.toBean(data.toString(), BmsBillMemo.class);
  17. System.out.println(bmsBillMemo);
  18. }

3.1.2getForEntity(String url, Class responseType, Map uriVariables)
解析:这里只有uriVariables这个参数不同,这里使用了Map类型,
注意:使用该方法进行参数绑定时需要在占位符中指定Map的key

请求接口

  1. @Slf4j
  2. @RestController
  3. @RequestMapping("/memo")
  4. public class BmsBillMemoController {
  5. @Autowired
  6. private IBmsBillMemoService bmsBillMemoService;
  7. /**
  8. * 查询结算账单手账列表
  9. */
  10. @GetMapping("/list")
  11. public TableDataInfo list(BmsBillMemo bmsBillMemo) {
  12. List<BmsBillMemo> list = bmsBillMemoService.selectBmsBillMemoList(bmsBillMemo);
  13. return getDataTable(list);
  14. }

请求代码

  1. @Test
  2. public void Rest2() {
  3. String url = "http://localhost:8080/memo/list?id={id}&clientName={clientName}";
  4. Class responseType = String.class;
  5. Map<String,String> map = new HashMap<>();
  6. map.put("id","3");
  7. map.put("clientName","顾客");
  8. ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, responseType, map);
  9. System.out.println("1 "+responseEntity.getStatusCode());
  10. System.out.println("2 "+responseEntity.getStatusCodeValue());
  11. System.out.println("3 "+responseEntity.getHeaders());
  12. System.out.println("4 "+responseEntity.getBody());
  13. String body = responseEntity.getBody();
  14. TableDataInfo result = JSONUtil.toBean(body, TableDataInfo.class);
  15. Object data = result.getRows();
  16. List<BmsBillMemo> bmsBillMemos = JSONUtil.toList(JSONUtil.parseArray(data.toString()), BmsBillMemo.class);
  17. bmsBillMemos.stream().forEach(System.out::println);
  18. }

3.1.3 getForEntity(URI url, Class responseType)
解析:该方法使用URI替换之前的url和urlVariables参数来指定访问地址和参数绑定。
例如:
RestTemplate restTemplate = new RestTemplate();
UriComponents uriComponenets = UriComponentsBuilder.formUriString{
“http://USER-SERVICE/user?name=\{name\}“
.build()
.expand(“dodo”)
.encode();
}
URI uri = UriComponents.toUri();
ResponseEntity responseEntity = restTemplate.getForEntity(uri,
String.class).getBody();

3.1.4 getForObject()函数

解析:它可以理解为getForEntity的进一步封装,它通过HttpMessageConverterExtractor对HTTP请求响应体body内容进行对象转换,实现请求直接返回包装好的对象内容
使用场景:当不需要关注请求响应除body外的其他内容时,该函数就非常好用,可以少一个从Response中获取body的步骤。

1.getForObject(String url, Class responseType, Object… uriVariables)
解析:url指定访问的地址,responseType指定访问的地址,urlVariables为url中占位符对应的参数
2.getForObject(String url, Class responseType, Map uriVariables)
解析:该函数使用Map类型的urlVariables替代上面数组形式的urlVariables,因此使用时在url中需要将占位符的名称与Map类型中的Key一一对应设置

3.getForObject(URI url, Class responseType)
解析:该方法使用URI对象来替换之前的url和urlVariabels参数使用

请求代码

  1. @Test
  2. public void Rest3() {
  3. String url = "http://localhost:8080/memo/{1}/{2}";
  4. Class<AjaxResult> responseType = AjaxResult.class;
  5. String [] str = new String[2];
  6. str[0] = "3";
  7. str[1] = "小林";
  8. AjaxResult ajaxResult = restTemplate.getForObject(url, responseType, str);
  9. Object data = ajaxResult.get("data");
  10. JSONObject jsonObject = JSONUtil.parseObj(data);
  11. System.out.println(jsonObject);
  12. // BmsBillMemo bmsBillMemo = JSONUtil.toBean(jsonObject, BmsBillMemo.class);
  13. BmsBillMemo bmsBillMemo = JSONUtil.toBean(JSONUtil.toJsonStr(data), BmsBillMemo.class);
  14. System.out.println(bmsBillMemo);
  15. }

3.2 POST请求

1.postForEntity(String url, Object request, Class responseType, Object… uriVariables)
2.postForEntity(String url, Object request, Class responseType, Map uriVariables)
3.postForEntity(URI url, Object request, Class responseType)

解析:重载函数中的uriVariables用来对url中的参数进行绑定,responseType参数是对请求响应的body内容的类型定义
注意:新增的request参数,改参数可以是一个普通的对象,也可以是一个HttpEntity对象。
如果request是一个普通对象时,RestTemplate会将这个普通对象转换成HttpEntity对象来处理,其中Object就是request的类型,request内容会被当成一个完整的body来处理;
如果resuqet是一个HttpEntity对象时,那么request会被当成一个完整的HTTP请求对象来处理,这个request中不仅包含了body内容,也包含了header的内容
下面的测试代码是第二种的,其他的和上面get的类似

请求接口

  1. /**
  2. * 查询结算账单手账列表
  3. */
  4. @PostMapping("/list1")
  5. public AjaxResult list1(@RequestBody BmsBillMemo bmsBillMemo, BmsBillMemo bmsBillMemo2) {
  6. List<BmsBillMemo> list = bmsBillMemoService.selectBmsBillMemoList(bmsBillMemo);
  7. List<BmsBillMemo> list2 = bmsBillMemoService.selectBmsBillMemoList(bmsBillMemo2);
  8. list.addAll(list2);
  9. return AjaxResult.success(list);
  10. }

请求代码

  1. @Test
  2. public void Rest5() {
  3. String url = "http://localhost:8080/memo/list1?clientId={clientId}&supplierId={supplierId}";
  4. Class responseType = String.class;
  5. HttpHeaders head = new HttpHeaders();
  6. head.add("Content-Type","application/json");
  7. //设置请求体参数
  8. BmsBillMemo memo = new BmsBillMemo();
  9. memo.setId(3l);
  10. memo.setClientId(8l);
  11. memo.setSupplierId(33l);
  12. //设置请求头参数
  13. Map<String,String> map = new HashMap<>();
  14. map.put("clientId","8");
  15. map.put("supplierId","66");
  16. HttpEntity<String> entity = new HttpEntity(JSONUtil.toJsonStr(memo),head);
  17. ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, responseType,map);
  18. System.out.println(responseEntity.getHeaders());
  19. System.out.println(responseEntity.getStatusCode());
  20. System.out.println(responseEntity.getStatusCodeValue());
  21. System.out.println(responseEntity.getBody());
  22. }
  23. HttpEntity中也可以换成具体的实体类对象
  24. @Test
  25. public void Rest5() {
  26. String url = "http://localhost:8080/memo/list1?clientId={clientId}&supplierId={supplierId}";
  27. Class responseType = String.class;
  28. HttpHeaders head = new HttpHeaders();
  29. head.add("Content-Type","application/json");
  30. //设置请求体参数
  31. BmsBillMemo memo = new BmsBillMemo();
  32. memo.setId(3l);
  33. memo.setClientId(8l);
  34. memo.setSupplierId(33l);
  35. //设置请求头参数
  36. Map<String,String> map = new HashMap<>();
  37. map.put("clientId","8");
  38. map.put("supplierId","66");
  39. HttpEntity<BmsBillMemo> entity = new HttpEntity(memo,head);
  40. ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, responseType,map);
  41. System.out.println(responseEntity.getHeaders());
  42. System.out.println(responseEntity.getStatusCode());
  43. System.out.println(responseEntity.getStatusCodeValue());
  44. System.out.println(responseEntity.getBody());
  45. }

4.postForObject()函数
解析:它简化了postForEntity()的后续处理,通过直接将请求响应的body内容包装陈对象来简化返回使用。
RestTemplate restTemplate = new RestTemplate();
User user = new User(“didi”, 20);
String postResult = restTemplate.postForObject(“http[://USER-SERVICE/user”, user, String.class);

三个重载方法:
postForObject(String url, Object request, Class responseType, Object… uriVariables)
postForObject(String url, Object request, Class responseType, Map uriVariables)
postForObject(URI url, Object request, Class responseType)

4 exchange

  1. exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables)

有关exchange方法,这边只介绍这一种,其他的基本类似

get请求代码

  1. @Test
  2. public void rest6(){
  3. String url = "http://localhost:8080/memo/list?id={id}&clientId={clientId}&clientName={clientName}";
  4. //设置请求头
  5. HttpHeaders head = new HttpHeaders();
  6. head.add("Content-Type","application/json");
  7. //封装请求体和请求头
  8. HttpEntity<String> entity = new HttpEntity<>(null,head);
  9. //设置请求返回值类型(一般设置为string,再进行转换)
  10. Class responseType = String.class;
  11. //设置请求url中的参数,可以用map或者数组
  12. Map<String,String> map = new HashMap<>();
  13. map.put("id","3");
  14. map.put("clientName","顾客");
  15. map.put("clientId","4");
  16. //发起请求
  17. ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET,entity,responseType, map);
  18. //判断请求状态并获取请求的结果
  19. System.out.println("1 "+responseEntity.getStatusCode());
  20. System.out.println("2 "+responseEntity.getStatusCodeValue());
  21. System.out.println("3 "+responseEntity.getHeaders());
  22. System.out.println("4 "+responseEntity.getBody());
  23. String body = responseEntity.getBody();
  24. TableDataInfo result = JSONUtil.toBean(body, TableDataInfo.class);
  25. Object data = result.getRows();
  26. List<BmsBillMemo> bmsBillMemos = JSONUtil.toList(JSONUtil.parseArray(data.toString()), BmsBillMemo.class);
  27. bmsBillMemos.stream().forEach(System.out::println);
  28. }

post请求代码

  1. @Test
  2. public void rest7() {
  3. String url = "http://localhost:8080/memo/list1?clientId={clientId}&supplierId={supplierId}";
  4. //设置请求头
  5. HttpHeaders head = new HttpHeaders();
  6. head.add("Content-Type", "application/json");
  7. //设置请求体参数
  8. BmsBillMemo memo = new BmsBillMemo();
  9. memo.setId(3l);
  10. memo.setClientId(8l);
  11. memo.setSupplierId(33l);
  12. //封装请求头和请求体
  13. HttpEntity<BmsBillMemo> entity = new HttpEntity(memo, head);
  14. //设置请求的返回类型(一般为String,便于共用)
  15. Class responseType = String.class;
  16. //设置请求头参数
  17. Map<String, String> map = new HashMap<>();
  18. map.put("clientId", "8");
  19. map.put("supplierId", "66");
  20. ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, responseType, map);
  21. System.out.println(responseEntity.getHeaders());
  22. System.out.println(responseEntity.getStatusCode());
  23. System.out.println(responseEntity.getStatusCodeValue());
  24. System.out.println(responseEntity.getBody());
  25. }

总结

还有常用的delete和put请求相对简单,这里就不一一介绍的,常用的请求中请求头中通常需要添加token进行访问,这点需要注意,

发表评论

表情:
评论列表 (有 0 条评论,143人围观)

还没有评论,来说两句吧...

相关阅读

    相关 restTemplate使用

    目录 目录 一、概述? 二、使用步骤 1.引入依赖 2.创建RestTemplate对象,交由spring容器进行管理 3.使用方法 3.1 GET请求