RestTemplate remote method invocation

Overview:

RestTemplate like spring framework can be used to call the rest service in the application that simplifies communication with http services, unified standard RESTful that encapsulates http link, we only need to pass url and return type can be. Commonly used HttpClient, RestTemplate is a more elegant calling RESTful services compared to the previous method.

use

The first is an example of the RestTemplate
 /*
    * 实例化restTemplate
    * */
    @Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
        for (HttpMessageConverter<?> httpMessageConverter : list) {
            if(httpMessageConverter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName("UTF-8"));
                break;
            }
        }
        return restTemplate;
    }

Method 9001 / user / {id} corresponding Controller layer: We have a further url: http: // cloud

Create a test method to build a unit TestController

RestTemplate you use remote call set http: // cloud: 9001 / user / {id} method

Users get to

/**
         * 参数一:调用url地址
         * 参数二:需要封装的对象类型
         */

       User user = restTemplate.getForObject("http://cloud:9001/user/"+id, User.class);
        System.out.println(user.getUsername()+"正在购票");
        return user.getUsername()+"购票成功!";

Guess you like

Origin www.cnblogs.com/liujunwei/p/11904700.html