一、什么是RestTemplate?
RestTemplate 是一個HTTP客戶端,在Spring Cloud的服務(wù)調(diào)用方使用它我們可以方便的調(diào)用HTTP接口,支持GET、POST、PUT、DELETE等方法。
二、四種請求方式
首先注入Bean對象
@Configuration
public class MyConfig {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
2.1 GET請求
- getForObject
@GetMapping("get/{id}")
public CommonResult getUser(@PathVariable Long id) {
CommonResult commonResult
= restTemplate.getForObject(Url + "/user/{1}", CommonResult.class, id);
return commonResult
}
- getForEntity
@GetMapping("/get/{sex}")
public CommonResult getUser(@PathVariable String sex) {
ResponseEntity<CommonResult> entity
= restTemplate.getForEntity(Url + "/user/{女}", CommonResult.class, sex);
if (entity.getStatusCode().is2xxSuccessful()) {
return entity.getBody();
} else {
return new CommonResult("操作失敗", 500);
}
}
2.2 POST請求
- postForObject
@PostMapping("/add")
public CommonResult add(@RequestBody User user) {
CommonResult commonResult
= restTemplate.postForObject(Url + "/user/add", user, CommonResult.class);
return commonResult;
}
- postForEntity
@PostMapping("/add")
public CommonResult add(@RequestBody User user) {
CommonResult commonResult
= restTemplate.postForEntity(Url + "/user/add", user, CommonResult.class)
return commonResult.getBody();
}
2.3 PUT請求
@PutMapping("/update")
public CommonResult update(@RequestBody User user) {
restTemplate.put(Url + "/user/update", user);
return new CommonResult("操作成功",200);
}
2.4 DELETE請求
@DeleteMapping("/delete/{id}")
public CommonResult delete(@PathVariable Long id) {
restTemplate.delete(Url + "/user/delete/" + id, null);
return new CommonResult("操作成功",200);
}
以上就是關(guān)于SpringCloud微服務(wù)中的Rest服務(wù)及其幾種請求方式的全部內(nèi)容,更多相關(guān)SpringCloud Rest內(nèi)容,請搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,也希望大家以后多多支持我們!