RestTemplate的超全讲解(全)转
RestTemplate的超全讲解(全)转
https://blog.csdn.net/weixin_47872288/article/details/121842374
(81条消息) RestTemplate的超全讲解(全)_码农研究僧的博客-CSDN博客_resttemplate
视频地址:
https://www.bilibili.com/video/BV1tJ41147uj?t=624.5&p=4
post与get的区别在于post的方法传参map必须是MultiValueMap
基本类型传参和实体类型传参
@RestController public class UserController{ //实体传参 @RequestMapping(value="/addUser1") public UserDTO addUser(userDTO userdto) { return userdto; } @ResquestMapping(value="/addUser2") public UserDTO addUser2(Long userId,String userName) { UserDTO u=new UserDTO(); u.setUserId(userId); u.setUserName(userName); return u; } }
Post 请求方式调用服务接口
//http://localhost:8080/postFor0bject1 @GetMapping("/postForObject1") public UserDT0 postForObject1 ( ) { //远程访问的Url UserDTO String url = "http://localhost:8080/addUser1"; // Post方法必须使用MultiValueMap传参。//使用UserDTO传参也可以 MultiValueMap<String,0bject> paramMap = new LinkedMultiValueMap<>(); paramMap.add ("userId", 1008L); paramMap.add ("userName ","巧克力"); UserDT0 userDTO = restTemplate.postForObject(url,paramMap,UserDT0.class); return userDTO; }
如果服务接口使用到@RequestBody
,用httpentity ,此时不能使用MultiValueMap 传参!!
@RequestMapping( value = "/addUser3" ) public UserDT0 addUser3(@RequestBody UserDT0 userDTO) { userDTo.setUserName(userDTo.getUserName() + " from RequestBody" ); return userDTO; }
//http://localhost:8888/postForObject2 @GetMapping("/postForObject2") public UserDT0 postForObject2( ) { //申明一个请求头 HttpHeaders headers = new HttpHeaders(); //application/json headers.setContentType( MediaType .APPLICATION_JSON);//远程访问的Url UserDTO string url = "http://localhost:8080/addUser3"; /** 此处使用MultiValueMap会报错 MultiValueMap<String,0bject> paramMap = new LinkedMultiValueMap<>( ); paramMap.add("userId",100OL) ; paramMap.add("userName","fencaibc");*/ //此处可以使用HashMap代替,但是会有警告 UserDT0 userDTO = new UserDTO( ); userDTO.setUserId( 1088L); userDT0.setUserName("课程"); HttpEntity<UserDTO> entityParam new HttpEntity<UserDTO>(userDTO,headers) ; UserDT0 result = restTemplate.postFor0bject(url, entityParam,UserDTO.class); return result ; }
PostForEntity 方法 返回内容比 postForObject 更丰富,但是要注意,基本类型的参数采用 MultiValueMap封装参数,@ReqeustBody 修饰的参数 要以httpEntity 封装对象实例作为参数
同时,返回结果要是 ResponseEntity类型
//http://localhost:8088/ postForEntity1@GetMapping( " / postForEntity1") public UserDT0 postForEntity1( ) { string url = "http://localhost:8080/addUser1" ; MultiValueMap<String,object> paramMap = new LinkedMultiValueMap<>( ); paramMap.add("userId", 100); paramMap.add("userName" ,"课程"); ResponseEntity<UserDT0> userDTOResponseEntity =restTemplate.postForEntity(url,paramMap,UserDTO.class) ; HttpStatus statusCode = userDTOResponseEntity.getStatusCode( ); int statusCodeValue = userDTOResponseEntity.getStatusCodeValue( ); HttpHeaders headers = userDTOResponseEntity. getHeaders( ); return userDTOResponseEntity. getBody( ); }
效果