利用Spring框架提供的Restemplate四种常见的请求方法
Get
getForEntity()-----返回响应头跟响应体
getForObject()-----只返回响应体
@GetMapping("/hello3")
public String sayHello3() throws IOException {
//url ,返回值类型
return restTemplateBalance.getForObject("http://provider/hello",String.class);
}
Post
在Get的基础上加了一个方法postForLocation()
这个是为了重定向,调用后,返回的uri就是重定向的地址;
注意:消费者的路由不再是@RestController了,普通@Controller就可
返回值大概是这样子:
return "redirect:http://provider/loginPage";
Put
跟Post差不多
Delete
消费者:
@GetMapping("/hello11")
public void delete(){
restTemplateBalance.delete("http://provider/delete/{1}",1);
restTemplateBalance.delete("http://provider/delete?id={1}",2);
}
提供者:
@DeleteMapping("/delete/{id}")
public void deleteByid1(@PathVariable Integer id){
System.out.println(id);
}
@DeleteMapping("/delete")
public void deleteByid2(Integer id){
System.out.println(id);
}
本文详细介绍了Spring框架中的RestTemplate如何使用GET、POST、PUT和DELETE这四种常见的HTTP请求方法。对于GET,提到了getForEntity和getForObject的区别;POST中重点讲解了postForLocation方法用于处理重定向的情况;PUT和DELETE方法则与POST类似,简单概述了它们的使用场景。
1万+

被折叠的 条评论
为什么被折叠?



