Spring中RestTemplate使用

Spring中RestTemplate使用

RestTemplate简介

在微服务都是以HTTP接口的形式暴露自身服务的,因此在调用远程服务时就必须使用HTTP客户端。我们可以使用JDK原生的URLConnection、Apache的Http Client、Netty的异步HTTP Client, Spring的RestTemplate。但是,用起来最方便、最优雅的还是要属Feign了。这里介绍的是RestTemplate。

RestTemplate是Spring提供的用于访问Rest服务的客户端,

RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。

调用RestTemplate的默认构造函数,RestTemplate对象在底层通过使用java.net包下的实现创建HTTP 请求,

可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式。

ClientHttpRequestFactory接口主要提供了两种实现方式

1、一种是SimpleClientHttpRequestFactory,使用J2SE提供的方式(既java.net包提供的方式)创建底层的Http请求连接。

2、一种方式是使用HttpComponentsClientHttpRequestFactory方式,底层使用HttpClient访问远程的Http服务,使用HttpClient可以配置连接池和证书等信息。

RestTemplate使用

  1. 初始化
    1
    2
    3
    4
    5
    6
    7
    8
    @Bean
    public RestTemplate restTemplate(){
    return new RestTemplate();
    }

    // 注入
    @Autowired
    RestTemplate restTemplate;

  1. GET请求
    在RestTemplate中,发送一个GET请求,我们可以通过如下两种方式:
    第一种:getForEntity
    getForEntity方法的返回值是一个ResponseEntity,ResponseEntity是Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    @RequestMapping("/gethello")
    public String getHello() {
    ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class);
    String body = responseEntity.getBody();
    HttpStatus statusCode = responseEntity.getStatusCode();
    int statusCodeValue = responseEntity.getStatusCodeValue();
    HttpHeaders headers = responseEntity.getHeaders();
    StringBuffer result = new StringBuffer();
    result.append("responseEntity.getBody():").append(body).append("<hr>")
    .append("responseEntity.getStatusCode():").append(statusCode).append("<hr>")
    .append("responseEntity.getStatusCodeValue():").append(statusCodeValue).append("<hr>")
    .append("responseEntity.getHeaders():").append(headers).append("<hr>");
    return result.toString();
    }
  • getForEntity的第一个参数为我要调用的服务的地址,这里我调用了服务提供者提供的/hello接口,注意这里是通过服务名调用而不是服务地址,如果写成服务地址就没法实现客户端负载均衡了。
  • getForEntity第二个参数String.class表示我希望返回的body类型是String
  • 拿到返回结果之后,将返回结果遍历打印出来

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

1
2
3
4
5
6
7
8
9
10
11
12
@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为参数值

第二种:getForObject
getForObject函数实际上是对getForEntity函数的进一步封装,如果你只关注返回的消息体的内容,对其他信息都不关注,此时可以使用getForObject

1
2
3
4
5
@RequestMapping("/book2")
public Book book2() {
Book book = restTemplate.getForObject("http://HELLO-SERVICE/getbook1", Book.class);
return book;
}

  1. POST请求

第一种:postForEntity
该方法和get请求中的getForEntity方法类似

1
2
3
4
5
6
7
@RequestMapping("/book3")
public Book book3() {
Book book = new Book();
book.setName("红楼梦");
ResponseEntity<Book> responseEntity = restTemplate.postForEntity("http://HELLO-SERVICE/getbook2", book, Book.class);
return responseEntity.getBody();
}

  • 方法的第一参数表示要调用的服务的地址
  • 方法的第二个参数表示上传的参数
  • 方法的第三个参数表示返回的消息体的数据类型

第二种:postForObject

如果只关注返回的消息体,可以直接使用postForObject。用法和getForObject一致。

第三种:postForLocation

postForLocation也是提交新资源,提交成功之后,返回新资源的URI,postForLocation的参数和前面两种的参数基本一致,只不过该方法的返回值为Uri,这个只需要服务提供者返回一个Uri即可,该Uri表示新资源的位置。

  1. PUT请求
    在RestTemplate中,PUT请求可以通过put方法调用,put方法的参数和前面介绍的postForEntity方法的参数基本一致,只是put方法没有返回值而已。
    1
    2
    3
    4
    5
    6
    @RequestMapping("/put")
    public void put() {
    Book book = new Book();
    book.setName("红楼梦");
    restTemplate.put("http://HELLO-SERVICE/getbook3/{1}", book, 99);
    }

  1. DELETE请求
    delete请求我们可以通过delete方法调用来实现
    1
    2
    3
    4
    @RequestMapping("/delete")
    public void delete() {
    restTemplate.delete("http://HELLO-SERVICE/getbook4/{1}", 100);
    }

来源:CSDN
原文:https://blog.csdn.net/u012702547/article/details/77917939