首页 > 行业资讯 > 正文

原文链接

GitHub项目地址

Gitee项目地址

本文介绍restTemplate基础用法。

Java中get和post的用法请参考:Java中Get和Post的使用

1 提供get/post接口

1.1 Controller

复制@RestController @RequestMapping(“/homepage”) public class MyController { @Autowired MyService myService; // 提供get接口 @GetMapping(“/provideGet”) public Map{ return myService.provideGet(); } // 提供post接口 @PostMapping(“/providePost”) public Map{ return myService.providePost(number, name); } // 提供map参数的post接口 @PostMapping(“/providePostByMap”) public Map{ return myService.providePostByMap(map); } // 调用get接口 @GetMapping(“/useGet”) public Map{ return myService.useGet(); } }

1.2 Service

复制@Service @EnableScheduling public class MyService { public Map{ Map 2 调用get/post接口

使用restTemplate调用get/post接口。

复制getForObject():返回值是复制HTTP协议的响应体 复制getForEntity():返回的是复制ResponseEntity,复制ResponseEntity是对复制HTTP响应的封装,除了包含响应体,还包含复制HTTP状态码、复制contentType、contentLength、Header等信息

2.1 Controller

复制@RestController @RequestMapping(“/homepage”) public class MyController { @Autowired MyService myService; // 调用get接口 @GetMapping(“/useGet”) public Map{ return myService.useGet(); } // 调用get接口验证账号密码 @GetMapping(“/useGetByPsw”) public Map{ return myService.useGetByPsw(); } // 调用post接口 @PostMapping(“/usePost”) public Map{ return myService.usePost(); } }

2.2 Service

复制@Service @EnableScheduling public class MyService { @Resource private RestTemplate restTemplate; String getURL = “http://localhost:8081/homepage/provideGet”; String postURL = “http://localhost:8081/homepage/providePostByMap”; public Map{ // getForObject返回值是HTTP协议的响应体 String strObject1 = restTemplate.getForObject(getURL, String.class); //无参 JSONObject jsonObject1 = JSONObject.parseObject(strObject1); MultiValueMap

猜你喜欢