Spring Boot Rest模板

package com.yiibai.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @Bean
   public RestTemplate getRestTemplate() {
      return new RestTemplate();
   }
}//原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/spring-boot/spring_boot_rest_template.html

GET

通过使用RestTemplate类的exchange()方法来使用GET API,
假设此URL => http://localhost:8080/products返回以下JSON,将使用以下代码使用Rest Template来使用此API响应 -

//原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/spring-boot/spring_boot_rest_template.html
[
   {
      "id": "1",
      "name": "Honey"
   },
   {
      "id": "2",
      "name": "Almond"
   }
]//原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/spring-boot/spring_boot_rest_template.html

必须遵循给定的点来使用API -

  • 自动装配Rest模板对象。
  • 使用HttpHeaders设置请求标头。
  • 使用HttpEntity包装请求对象。
  • Exchange()方法提供URL,HttpMethod和Return类型。
//原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/spring-boot/spring_boot_rest_template.html
@RestController
public class ConsumeWebService {
   @Autowired
   RestTemplate restTemplate;

   @RequestMapping(value = "/template/products")
   public String getProductList() {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity <String> entity = new HttpEntity<String>(headers);

      return restTemplate.exchange("
         http://localhost:8080/products", HttpMethod.GET, entity, String.class).getBody();
   }
}//原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/spring-boot/spring_boot_rest_template.html
原文地址:https://www.cnblogs.com/0710whh/p/12391068.html