zoukankan      html  css  js  c++  java
  • Spring Boot Rest模板

    POST

    通过使用RestTemplateexchange()方法来使用POST API

    假设此URL => http://localhost:8080/products返回如下所示的响应,使用Rest模板测试此API响应。

    下面给出的代码是请求正文 -

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

    需要遵循以下给出的要点来使用API -

    • 自动装配Rest模板对象。
    • 使用HttpHeaders设置请求标头。
    • 使用HttpEntity包装请求对象。 在这里将Product对象包装起来以将其发送到请求主体。

    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", method = RequestMethod.POST)
       public String createProducts(@RequestBody Product product) {
          HttpHeaders headers = new HttpHeaders();
          headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
          HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);
    
          return restTemplate.exchange(
             "http://localhost:8080/products", HttpMethod.POST, entity, String.class).getBody();
       }
    }//原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/spring-boot/spring_boot_rest_template.html
  • 相关阅读:
    git clone GitLab 工程报错Repository not found
    vue + Element-ui 实现分页
    Element-ui 实现table的合计功能
    python 使用UUID库生成唯一ID
    css 设置overflow:scroll 滚动条的样式
    下载css-loader 安装及使用
    vue实现首页导航切换不同路由的方式(二)【使用vuex实现的】
    vue实现随机验证码功能
    vue实现首页导航切换不同路由的方式
    vue实现菜单切换
  • 原文地址:https://www.cnblogs.com/0710whh/p/12391072.html
Copyright © 2011-2022 走看看