Introduction and use example of Spring Web RestTemplate

RestTemplate is a synchronous Http client request template tool. An abstraction of what the Spring framework does.

The official document address is as follows:

https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#rest-resttemplate

RestTemplate uses HttpUrlConnection by default, and the underlying execution engine can be replaced by construction methods. The common execution engines are HttpClient, Netty and OkHttp. References are as follows:

The default constructor uses java.net.HttpURLConnection to perform requests. You can switch to a different HTTP library with an implementation of ClientHttpRequestFactory. There is built-in support for the following:

  • Apache HttpComponents

  • Netty

  • OkHttp

For example, to switch to Apache HttpComponents, you can use the following: RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory());

Bean configuration class of RestTemplate

@Configuration
public class RestConf {
	//By default, the underlying execution engine HttpUrlConnection is used
    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

Or you can use Apache HttpComponents (HttpClient):

RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory());

User entity class used in this example

public class User {

    //User id
    private int id;
    //User name
    private String name;
}

HTTP GET request

RestTemplate has two core methods to perform Get requests

  1. The RestTemplate.getForObject method can get objects
  2. The RestTemplate.getForEntity method can get not only the object, but also the Http status code, request header and other details.

Rest controller for receiving HTTP requests

    @RequestMapping(value = "/addUser/{id}/{name}")
    public User addUser(@PathVariable("id") Integer id,
                        @PathVariable("name") String name){
        User user = new User();
        user.setId(id);
        user.setName(name);
        return user;
    }
  • RestTemplate.getForObject request example
    @GetMapping("/getForObject")
    public Object getForObject(){
        //Remote access Url User
        String url = "http://localhost:8088/addUser/100/Tom";
        //Request to join
        Map<String,Integer> paraMap= new HashMap<>();
        User result = restTemplate.getForObject(url, User.class,paraMap);
        return result;
    }
  • RestTemplate.getForEntity request example
    @GetMapping("/getForEntity")
    public Map<String,Object> getForEntity(){
        //Remote access Url User
        String url = "http://localhost:8088/addUser/100/Tom";
        //Empty entry parameter
        Map<String,Integer> paraMap= new HashMap<>();

        // ResponseEntity wrapper returns results
        ResponseEntity<HashMap> responseEntity = restTemplate.getForEntity(url, HashMap.class,paraMap);
        //Return status code packing class
        HttpStatus statusCode = responseEntity.getStatusCode();
        //Return status code
        int statusCodeValue = responseEntity.getStatusCodeValue();
        //Http return header
        HttpHeaders headers = responseEntity.getHeaders();
        HashMap body = responseEntity.getBody();
        return body;
    }

HTTP POST request

The Post method of RestTemplate supports Map parameter passing, ResponseBody parameter passing, and the parameter Map of Post method must be MultiValueMap

The MultiValueMap of Post method supports both separate parameter transfer of basic types and entity parameter transfer. Similar to the following parameter forms:

    //Entity reference
    @RequestMapping(value = "/addUserEntity")
    public User addUserEntity(User user){
        return user;
    }

    //Basic type parameters
    @RequestMapping(value = "/addUserBase")
    public User addUserBase(Integer id,String name){
        User user = new User();
        user.setId(id);
        user.setName(name);
        return user;
    }
  • RestTemplate.postForObject request example
  1. Example of MultiValueMap parameter transfer:
@GetMapping("/postForObject1")
public User postForObject1(){
    //Remote access Url User uses entity to transfer parameters
    String url = "http://localhost:8088/addUserEntity";
    //The Post method must use MultiValueMap parameters.
    MultiValueMap<String,Object> paraMap= new LinkedMultiValueMap<>();
    paraMap.add("id",123);
    paraMap.add("name","Tom");
    // ResponseEntity wrapper returns results
    User user = restTemplate.postForObject(url,paraMap, User.class);
    return user;
}

Of course, you can also use the following URL (the rest of the code remains the same)

 //Remote access Url basic type parameters
 String url = "http://localhost:8088/addUserBase";
  1. @The ResponseBody parameter is passed in the form of HttpEntity

Reception form of Rest controller:

    //@ResponseBody parameters
    @RequestMapping(value = "/addUserBody")
    public User addUserBody(@RequestBody User user){
        user.setName(user.getName()+" from RequestBody");
        return user;
    }

Use HttpEntity to pass parameters:

    @GetMapping("/postForObject2")
    public User postForObject2(){
        // Declare a request header
        HttpHeaders headers = new HttpHeaders();
        //application/json
        headers.setContentType(MediaType.APPLICATION_JSON);
        //Remote access Url User
        String url = "http://localhost:8088/addUserBody";
        /**
         * Note that error will be reported when using MultiValueMap here
         * MultiValueMap<String,Object> paraMap= new LinkedMultiValueMap<>();
         * paraMap.add("id",123);
         * paraMap.add("name","Tom");
         *
         */
        //HashMap can be used instead here with warnings.
        User user = new User();
        user.setId(126);
        user.setName("Jack");
        //Use HttpEntity to pass parameters
        HttpEntity<User> entityParam= new HttpEntity<User>(user,headers);
        // ResponseEntity wrapper returns results
        User result = restTemplate.postForObject(url,entityParam, User.class);
        return result;
    }
  • RestTemplate.postForEntity request example

The only difference between postForEntity and postforebject is that they use responseentity < user > when returning, and the others are the same.

    @GetMapping("/postForEntity1")
    public User postForEntity1(){
        //Remote access Url User
        String url = "http://localhost:8088/addUserEntity";
        //Remote access Url basic type parameters
        //String url = "http://localhost:8088/addUserBase";
        //The Post method must use MultiValueMap arguments.
        //You can also use the User parameter
        MultiValueMap<String,Object> paraMap= new LinkedMultiValueMap<>();
        paraMap.add("id",123);
        paraMap.add("name","Tom");

        // ResponseEntity wrapper returns results
        ResponseEntity<User> responseEntity = restTemplate.postForEntity(url,paraMap,User.class);
        //Return status code packing class
        HttpStatus statusCode = responseEntity.getStatusCode();
        //Return status code
        int statusCodeValue = responseEntity.getStatusCodeValue();
        //Http return header
        HttpHeaders headers = responseEntity.getHeaders();
        return responseEntity.getBody();
    }

RestTemplate Exchange

When using Exchange, you need to specify the calling method, return to use ResponseEntity, and request to use HttpEntity:

    @GetMapping("/exchange")
    public User exchange(){
        //Remote access Url User
        String url = "http://localhost:8088/addUserEntity";
        //Remote access Url basic type parameters
        //String url = "http://localhost:8088/addUserBase";
        //Using MultiValueMap to transfer parameters
        MultiValueMap<String,Object> paraMap= new LinkedMultiValueMap<>();
        paraMap.add("id",123);
        paraMap.add("name","Tom");

        //Use HttpEntity to pass parameters
        HttpEntity<MultiValueMap> entityParam= new HttpEntity<>(paraMap);
        // ResponseEntity wrapper returns results
        ResponseEntity<User> responseEntity = restTemplate.exchange(url,HttpMethod.POST, entityParam,User.class);
        return responseEntity.getBody();
    }

Tags: Programming Spring REST Apache Netty

Posted on Wed, 22 Apr 2020 10:38:21 -0700 by tomwhalen