Spring RestTemplate的使用

 Spring Boot在1.4版本及之后,Spring Boot不再自动定义一个RestTemplate,而是定义了一个RestTemplateBuilder,允许您更好地控制RestTemplate的对象。你可以在标注了@Bean注解的方法中注入一个RestTemplateBuilder对象的参数来创建一个RestTemplate:(也就是说使用RestTemplate需要添加一个配置类)

@Configuration
 public class RestTemplateConfig {
     @Bean
     public RestTemplate restTemplate(RestTemplateBuilder builder) {
         return builder.build();
     }
 }

然后就可以自动装配RestTemplate:

@Autowiredprivate 
RestTemplate restTemplate;

GET请求

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

第一种:getForEntity

getForEntity方法的返回值是一个ResponseEntity<T>,ResponseEntity<T>是Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等。比如下面一个例子:

@RequestMapping("/gethello")
public String getHello() {
 
    ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class);
String body = responseEntity.getBody();
    return body ;
}

关于这段代码,我说如下几点:

getForEntity的第一个参数为我要调用的服务的地址,这里我调用了服务提供者提供的/hello接口,注意这里是通过服务名调用而不是服务地址,如果写成服务地址就没法实现客户端负载均衡了。

getForEntity第二个参数String.class表示我希望返回的body类型是String.

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

@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为参数值

第一个调用地址也可以是一个URI而不是字符串,这个时候我们构建一个URI即可,参数神马的都包含在URI中了,如下:

@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();
}

当然,服务提供者不仅可以返回String,也可以返回一个自定义类型的对象,比如我的服务提供者中有如下方法:

@RequestMapping(value = "/getbook1", method = RequestMethod.GET)
public Book book1() {
    return new Book("三国演义", 90, "罗贯中", "花城出版社");
}

对于该方法我可以在服务消费者中通过如下方式来调用:

@RequestMapping("/book1")
public Book book1() {
    ResponseEntity<Book> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/getbook1", Book.class);
    return responseEntity.getBody();
}

运行结果如下:

Spring RestTemplate 封装java工具类 spring resttemplate 配置_RestTemplate

第二种:getForObject

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

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

POST请求

在RestTemplate中,POST请求可以通过如下三个方法来发起:

第一种:postForEntity

该方法和get请求中的getForEntity方法类似,如下例子:

@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();
}

方法的第一参数表示要调用的服务的地址

方法的第二个参数表示上传的参数

方法的第三个参数表示返回的消息体的数据类型

我这里创建了一个Book对象,这个Book对象只有name属性有值,将之传递到服务提供者那里去,服务提供者代码如下:

@RequestMapping(value = "/getbook2", method = RequestMethod.POST)
public Book book2(@RequestBody Book book) {
    System.out.println(book.getName());
    book.setPrice(33);
    book.setAuthor("曹雪芹");
    book.setPublisher("人民文学出版社");
    return book;
}

服务提供者接收到服务消费者传来的参数book,给其他属性设置上值再返回,调用结果如下:

Spring RestTemplate 封装java工具类 spring resttemplate 配置_封装_02

exchange方法

restTemplate.exchange(
        String url, 
        HttpMethod method,
        HttpEntity requestEntity, 
        Class responseType, 
        Object uriVariables[]
)

说明:1)url: 请求地址;2)method: 请求类型(如:POST,PUT,DELETE,GET);3)requestEntity: 请求实体,封装请求头,请求内容4)responseType: 响应类型,根据服务接口的返回类型决定5)uriVariables: url中参数变量值 

post请求自定义header

@RequestMapping("/headerApi")//模拟远程的restful API
    public JSONObject withHeader(@RequestBody JSONObject parm, HttpServletRequest req){
        System.out.println("headerApi====="+parm.toJSONString());
        Enumeration<String> headers = req.getHeaderNames();
        JSONObject result = new JSONObject();
        while(headers.hasMoreElements()){
            String name = headers.nextElement();
            System.out.println("["+name+"]="+req.getHeader(name));
            result.put(name, req.getHeader(name));
        }
        result.put("descp", "this is from header");
        return result;
    }
 
    @RequestMapping("/header")
    public Object postWithHeader(){
//该方法通过restTemplate请求远程restfulAPI
        HttpHeaders headers = new HttpHeaders();
        headers.set("auth_token", "asdfgh");
        headers.set("Other-Header", "othervalue");
        headers.setContentType(MediaType.APPLICATION_JSON);
        
        JSONObject parm = new JSONObject();
        parm.put("parm", "1234");
        HttpEntity<JSONObject> entity = new HttpEntity<JSONObject>(parm, headers);
        HttpEntity<String> response = restTemplate.exchange(
                "http://localhost:8080/headerApi", HttpMethod.POST, entity, String.class);//这里放JSONObject, String 都可以。因为JSONObject返回的时候其实也就是string
        return response.getBody();
    }