zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Webpack教程二
    Webpack教程一
    整个互联网行业都缺前端工程师?
    Sublime Text 3 搭建 React.js 开发环境
    Javascript的9张思维导图学习
    实现字体外部有描边
    CSS样式重置
    vue使用过滤器 filters:{}
    修改select的默认样式
    onmouseover和onmouseout鼠标移入移出切换图片的几种实现方法
  • 原文地址:https://www.cnblogs.com/0710whh/p/12391068.html
Copyright © 2011-2022 走看看