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

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

 @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

2.使用

 @Autowired
 private RestTemplate restTemplate;

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

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

接收方

@GetMapping("Hello")
    public String Hello(){
        return "Hello";
}

【2】
发送方

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

接收方

@GetMapping("Hello/{str}")
    public String Hello(@PathVariable String str){
        return str;
}

【3】
发送方

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

接收方

 @GetMapping("/test/{name}")
    public String test(@PathVariable String name){
        return name;
    }

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

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

接收方

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

【2】
发送方

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

接收方

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

三.参考
RestTemplate post请求传递map。

RestTemplate post请求传参方式

Spring RestTemplate中几种常见的请求方式

RestTemplate 的传参方式(Get、Put、Post)

RestTemplate 用法详解

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐