RestTemplate远程调用接口 完整代码!!!

使用的是mybatis-plus完成CRUD

  1. 配置类:
/**
 * @author: 
 * RestTemplate工具类,主要用来提供RestTemplate对象
 */

@Configuration//加上这个注解作用,可以被Spring扫描
public class RestTemplateConfig {
    /**
     * 创建RestTemplate对象,将RestTemplate对象的生命周期的管理交给Spring
     *
     * @return
     */
    @Bean
    public RestTemplate add() {
        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));//支持中文编码
        return restTemplate;
    }
}
  1. controller类 这里只介绍比较常用的两个调用方法 id详情查询 ,添加

  @Resource
  private RestTemplate restTemplate;



	//远程添加方法
    @GetMapping("/add")
    public void add(Supplier supplier) {
        supplierService.save(supplier);
    }
  
  /**
     * 调用远程添加方法  url 远程的添加路径
     * @param suppQuery
     * @return
     */
    @PostMapping("/restTemplate/add")
    public ResponseEntity<String> add(SuppQuery suppQuery) {
        ResponseEntity<String> entity = restTemplate.postForEntity("http://localhost:8088/add", suppQuery, String.class);
        System.out.println("suppQuery = " + suppQuery);
        return entity;
    }
    
//SuppQuery类 是远程要添加的javabean
@Data
//封装对象
public class SuppQuery {
 
    private String gid;
  
    private String name;
        
    private String customEmail;  
}
  1. 根据id查询 远程调用
    //远程端接口
    @GetMapping("/detail/{id}")
    public Supplier findAll2(@PathVariable("id") String gid) {
        Supplier byId = supplierService.getById(gid);
        return byId;
    }


       //调用远程接口  
        @GetMapping(value = "/restTemplate/{gid}")
        public void download(@PathVariable("gid") String gid) throws IOException {
            //訪問url + token
            String url1 = "http://localhost:8088/detail/" + gid;
            //远程请求
            SuppQuery forObject = restTemplate.getForObject(url1, SuppQuery.class);
            System.out.println("远程user数据 = " + forObject);
            String customName = forObject.getCustomName();
            System.out.println("customName = " + customName);
           
        }
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值