SpringBoot使用RestTemplate

た 入场券 2022-10-18 01:28 277阅读 0赞

一.RestTemplate简介
Spring RestTemplate 是 Spring 提供的用于访问 Rest 服务的客户端,RestTemplate 提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率,所以很多客户端比如 Android或者第三方服务商都是使用 RestTemplate 请求 restful 服务。

二.实战应用
1.创建实例

  1. @Bean
  2. public RestTemplate restTemplate() {
  3. return new RestTemplate();
  4. }

2.使用

  1. @Autowired
  2. private RestTemplate restTemplate;

(1)get请求——-get请求是通过url传递参数
【1】无参
发送方

  1. String url = "http://localhost:8081/Student/Hello";
  2. ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
  3. String body = forEntity.getBody();

接收方

  1. @GetMapping("Hello")
  2. public String Hello(){
  3. return "Hello";
  4. }

【2】
发送方

  1. String str ="你好";
  2. String url = "http://localhost:8081/Student/Hello/";
  3. ResponseEntity<String> forEntity = restTemplate.getForEntity(url+str, String.class);
  4. String body = forEntity.getBody();

接收方

  1. @GetMapping("Hello/{str}")
  2. public String Hello(@PathVariable String str){
  3. return str;
  4. }

【3】
发送方

  1. String name = "陈鹏";
  2. HashMap<String, String> map = new HashMap<>();
  3. map.put("name",name);
  4. String url = "http://localhost:8081/Test/test/{name}";
  5. ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, map);
  6. return responseEntity.getBody();

接收方

  1. @GetMapping("/test/{name}")
  2. public String test(@PathVariable String name){
  3. return name;
  4. }

(2)post请求方式
【1】
发送方

  1. Student stu = new Student("陈鹏",12);
  2. String url = "http://localhost:8081/Test/test/";
  3. ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,stu,String.class);
  4. return responseEntity.getBody();

接收方

  1. @PostMapping("/test")
  2. public String test(@RequestBody Student student){
  3. return student.toString();
  4. }

【2】
发送方

  1. HttpHeaders headers = new HttpHeaders();
  2. headers.setContentType(MediaType.APPLICATION_JSON_UTF8);//设置参数类型和编码
  3. Student student = new Student("陈",15);
  4. Map<String,Student> map = new HashMap<>();
  5. map.put("student",student);
  6. HttpEntity<Map<String,Student>> request1 = new HttpEntity<>(map, headers);//包装到HttpEntity
  7. //postForEntity -》 直接传递map参数
  8. ResponseEntity<String> respo = restTemplate.postForEntity("http://localhost:8081/Test/test", map, String.class);
  9. return respo.getBody();

接收方

  1. @PostMapping("/test")
  2. public String test(@RequestBody Map<String, Student> map){
  3. Student student = map.get("student");
  4. return student.toString();
  5. }

三.参考
RestTemplate post请求传递map。
RestTemplate post请求传参方式
Spring RestTemplate中几种常见的请求方式
RestTemplate 的传参方式(Get、Put、Post)
RestTemplate 用法详解

发表评论

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

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

相关阅读