SpringCloud(3) ------>RestTemplate调用接口示例

RestTemplate是一个HTTP客户端,使用它我们可以方便的调用HTTP接口,支持GETPOSTPUTDELETE等方法。

一、getForObject方法

1、通过RestTemplate发送Get请求

 wordAppUrl为服务地址:例如http://word-app

 word-app为服务名称

 @GetMapping("/findAllWord")
    public CommonResult findAllWord(@RequestParam String userCode) {
        return restTemplate.getForObject(wordAppUrl + "/word/findWordByUserCode?userCode={1}", CommonResult.class, userCode);
    }
 @GetMapping("/findWordById2")
    public CommonResult findWordById2(@RequestParam Integer id) {
        return restTemplate.getForObject(wordAppUrl + "/word/findById2?id={1}", CommonResult.class, id);
    }

2、通过RestTemplate发送Post请求

  /**
     * 根据Id集合查询
     * postForObject 测试
     */
    @GetMapping("/findWordByIds")
    public CommonResult findWordByIds() {
        Integer[] ids = {1,2,3};
        return restTemplate.postForObject(wordAppUrl + "/word/findByIds",ids, CommonResult.class);
    }
   /**
     * postForObject 测试
     */
    @GetMapping("/createWord")
    public CommonResult createWord() {
        Word word = Word.builder().id(101).chinese("自己").english("self").author("liangd").commitTime(new Date()).build();
        return restTemplate.postForObject(wordAppUrl + "/word/create", JSONObject.toJSON(word), CommonResult.class);
    }

3、通过RestTemplate发送Put请求

    /**
     * put 测试
     */
    @GetMapping("/updateWord")
    public CommonResult updateWord() {
        Word word = Word.builder().id(101).chinese("爱好").english("hobby").author("liangd").commitTime(new Date()).build();
        restTemplate.put(wordAppUrl + "/word/update", JSONObject.toJSON(word),CommonResult.class);
        return CommonResult.success(null);
    }

4、通过RestTemplate发送Delete请求

  /**
     * delete 测试
     */
    @GetMapping("/deleteWord")
    public CommonResult deleteWord() {
        Integer id = 101;
        restTemplate.delete(wordAppUrl + "/word/delete?id={1}", id);
        return CommonResult.success(null);
    }

 

二、getForEntity方法

  返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等,

@GetMapping("/findWordById1/{id}")
    public CommonResult findWordById1(@PathVariable Integer id) {
        ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(wordAppUrl + "/word/findById1/{1}", CommonResult.class, id);
        System.out.println(forEntity);
        return forEntity.getBody();
    }

 

三、配置RestTemplate

@Configuration
public class RibbonConfig {
    /**
     * /使用@LoadBalanced注解赋予RestTemplate负载均衡的能力,默认是线性轮询的方式
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

 

原文地址:https://www.cnblogs.com/donleo123/p/14269192.html