美文网首页软件测试
spring详解 RestTemplate 操作

spring详解 RestTemplate 操作

作者: 张鹏宇_42ef | 来源:发表于2018-09-04 18:18 被阅读3次

    当我们从服务消费端去调用服务提供者的服务的时候,使用了一个很好用的对象,叫做RestTemplate,接下来我们详细的对RestTemplate的用法做一下解析

    1.本文主要从以下常用的2个方面来看RestTemplate的使用:

    GET请求 POST请求

    1.GET请求

    在RestTemplate中,发送一个GET请求,我们可以通过如下两种方式:

    第一种:getForEntity和getForObject

    (1)getForEntity方法的返回值是一个ResponseEntity,ResponseEntity是Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等。
    (2)getForObject() 方法用来只获取 响应体信息.
    getForObject 和 getForEntity 用法几乎相同,只是返回值返回的是 响应体,省去了我们 再去 getBody()
    (3)自我感觉,一般代码中应使用getForEntity方法,我们可以先判断响应码,然后再去获取请求体,个人意见,不喜勿喷,在这里,我们只讲getForEntity方法的使用。

    无参数的 getForObject 请求

       public List<UserEntity> getAll2() {
           ResponseEntity<List> responseEntity = restTemplate.getForEntity("http://localhost/getAll", List.class);
           HttpHeaders headers = responseEntity.getHeaders();
           HttpStatus statusCode = responseEntity.getStatusCode();
           int code = statusCode.value();
           //statusCode.is2xxSuccessful();判断状态码是否为2开头的
    
           List<UserEntity> list = responseEntity.getBody();
    
           System.out.println(list.toString());
           return list;
    
       }
    

    注意,返回值是List就是List.class,返回值是对象,就写对应的对象

    有时候我在调用服务提供者提供的接口时,可能需要传递参数,有两种不同的方式,如下:

    @RequestMapping("/sayhello")
    public String sayHello() {
        ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/sayhello?name={1}", String.class, "张三");
        return responseEntity.getBody();
    }
    @RequestMapping("/sayhello2")
    public String sayHello2() {
        Map<String, String> map = new HashMap<>();
        map.put("name", "李四");
        ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/sayhello?name={name}", String.class, map);
        return responseEntity.getBody();
    }
    
    • 可以用一个数字做占位符,最后是一个可变长度的参数,来一一替换前面的占位符
    • 也可以前面使用name={name}这种形式,最后一个参数是一个map,map的key即为前边占位符的名字,map的value为参数值
    • 如果你想对一个参数用一个URL来代替一长串的字符串,那你只能用UriComponents来构建你的URL
    @RequestMapping("/sayhello3")
    public String sayHello3() {
        UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://HELLO-SERVICE/sayhello?name={name}").build().expand("王五").encode();
        URI uri = uriComponents.toUri();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);
        return responseEntity.getBody();
    }
    

    2.Post请求

    (1)了解了get请求后,Post请求就变得很简单了,第一个参数是 URL,第二个参数是入参,第三个参数是返回参数,第四个参数如果有的话是URL后边拼接的东西

       // 有参数的 postForEntity 请求
        @RequestMapping("saveUserByType/{type}")
        public String save2(UserEntity userEntity,@PathVariable("type")String type) {
    
            ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost/saveByType/{type}", userEntity, String.class, type);
            String body = responseEntity.getBody();
    
            return body;
    
        }
    
        // 有参数的 postForEntity 请求,使用map封装
        @RequestMapping("saveUserByType2/{type}")
        public String save3(UserEntity userEntity,@PathVariable("type")String type) {
            HashMap<String, String> map = new HashMap<>();
             map.put("type", type);
    
    
            ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost/saveByType/{type}", userEntity, String.class,map);
            String body = responseEntity.getBody();
    
            return body;
    
        }
    

    相关文章

      网友评论

        本文标题:spring详解 RestTemplate 操作

        本文链接:https://www.haomeiwen.com/subject/yvyiwftx.html