spring boot 中訪問 REST 接口


RestTemplate restTemplate = new RestTemplate();
Object result = restTemplate.getForObject("https://www.baidu.com", String.class);

@Controller
 public class RestTemplateAction {
  
      @Autowired
      private RestTemplate template;
 
     @RequestMapping("RestTem")
     public @ResponseBody User RestTem(String method) {
         User user = null;
         //查找
         if ("get".equals(method)) {
             user = template.getForObject(
                     "http://localhost:8080/tao-manager-web/get/{id}",
                     User.class, "嗚嗚嗚嗚");
             
             //getForEntity與getForObject的區別是可以獲取返回值和狀態、頭等信息
             ResponseEntity<User> re = template.
                     getForEntity("http://localhost:8080/tao-manager-web/get/{id}",
                     User.class, "嗚嗚嗚嗚");
             System.out.println(re.getStatusCode());
             System.out.println(re.getBody().getUsername());
             
         //新增
         } else if ("post".equals(method)) {
             HttpHeaders headers = new HttpHeaders();
             headers.add("X-Auth-Token", UUID.randomUUID().toString());
             MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();
             postParameters.add("id", "啊啊啊");
             postParameters.add("name", "部版本");
             HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
                     postParameters, headers);
             user = template.postForObject(
                     "http://localhost:8080/tao-manager-web/post/aaa", requestEntity,
                     User.class);
         //刪除
         } else if ("delete".equals(method)) {
             template.delete("http://localhost:8080/tao-manager-web/delete/{id}","aaa");
         //修改
         } else if ("put".equals(method)) {
             template.put("http://localhost:8080/tao-manager-web/put/{id}",null,"bbb");
         }
         return user;
 
     }
 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM