spring详解 RestTemplate 操作

当我们从服务消费端去调用服务提供者的服务的时候,使用了一个很好用的对象,叫做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 Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,067评论 19 139
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 22,604评论 1 92
  • 简介 Spring Cloud Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix ...
    Chandler_珏瑜阅读 251,716评论 22 183
  • 1.你如何看待旧人?A.旧人是劣等种族必将灭绝。B.旧人有一定能力应该被圈养。 可儿看着这道题,愣了一下,这是什么...
    刀疤儿阅读 423评论 0 2
  • 今天晚上,我们去看了一场盛大的表演,又见敦煌讲了丝绸之路中敦煌从古至今的变化。 其中,第三募是一女睡在榻上,那...
    初二3班杨英杰阅读 477评论 0 0