Always using resttemplate? Have you really figured it out?

Time:2021-10-23

Send get request

<T> ResponseEntity<T> getForEntity(URI var1, Class<T> var2)

/*client*/
@Test
public void testRest(){
      RestTemplate restTemplate = new RestTemplate();
      String getUrl = "http://localhost:8083/mock/test/get" + "/" + "helloworld";
      ResponseEntity<Student> entity = restTemplate.getForEntity(getUrl,Student.class);
      log.info(entity.toString());
      log.info(entity.getHeaders().toString());
      log.info(entity.getBody().toString());
}

Client output log:
2020-05-27 09:14:44 [main] info apptest – < 200, student (name = Wang Jie, age = 28), [content type: “application / JSON”, transfer encoding: “chunked”, date: “wed, 27 May 2020 01:14:44 GMT”, keep alive: “timeout = 60”, connection: “keep alive”] >
2020-05-27 09:14:44 [main] INFO AppTest -[Content-Type:”application/json”, Transfer-Encoding:”chunked”, Date:”Wed, 27 May 2020 01:14:44 GMT”, Keep-Alive:”timeout=60″, Connection:”keep-alive”]
2020-05-27 09:14:44 [main] info apptest – student (name = Wang Jie, age = 28)

/*server*/
@RestController
@Slf4j
public class Demo {

    @GetMapping("/test/get/{name}")
    public JSONObject get(@PathVariable("name") String username){
        Log.debug ("get server called");
        log.info(username);
        JSONObject result = new JSONObject();
        Result.put ("name", "Wang Jie");
        result.put("age",28);
        return result;
    }
}

Server output log:
2020-05-27 09:14:44 [http-nio-8083-exec-3] debug com.ai.mock.resets.demo – get server called
2020-05-27 09:14:44 [http-nio-8083-exec-3] INFO com.ai.mock.rests.Demo -helloworld

<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables)

/*client*/
@Test
public void testRest2(){
    RestTemplate restTemplate = new RestTemplate();
    String getUrl = "http://localhost:8083/mock/test/get2?name={name}&age={age}";
    Map<String,Object> map = new HashMap<>();
    Map.put ("name", "skin shrimp");
    map.put("age",3);
    ResponseEntity<Student> entity = restTemplate.getForEntity(getUrl,Student.class,map);
    log.info(entity.toString());
    log.info(entity.getHeaders().toString());
    log.info(entity.getBody().toString());
    /*Verify that the student object is placed in the entity*/
    Student s = entity.getBody();
    log.info(s.getName());
    log.info(s.getAge().toString());
}

Client output log:
2020-05-27 09:26:34 [main] info apptest – < 200, student (name = Wang Jie, age = 28), [content type: “application / JSON”, transfer encoding: “chunked”, date: “wed, 27 May 2020 01:26:34 GMT”, keep alive: “timeout = 60”, connection: “keep alive”] >
2020-05-27 09:26:34 [main] INFO AppTest -[Content-Type:”application/json”, Transfer-Encoding:”chunked”, Date:”Wed, 27 May 2020 01:26:34 GMT”, Keep-Alive:”timeout=60″, Connection:”keep-alive”]
2020-05-27 09:26:34 [main] info apptest – student (name = Wang Jie, age = 28)
2020-05-27 09:26:34 [main] info apptest – Wang Jie
2020-05-27 09:26:34 [main] INFO AppTest -28

/*server*/
@GetMapping("/test/get2")
public JSONObject get2(@RequestParam("name") String username,@RequestParam("age") Integer age){
    Log.debug ("get server called");
    log.info("username=" + username);
    log.info("age=" + age);
    JSONObject result = new JSONObject();
    Result.put ("name", "Wang Jie");
    result.put("age",28);
    return result;
}

Server output log:
2020-05-27 09:26:34 [http-nio-8083-exec-2] debug com.ai.mock.resets.demo – get server called
2020-05-27 09:26:34 [http-nio-8083-exec-2] info com.ai.mock.resets.demo – username = shrimps
2020-05-27 09:26:34 [http-nio-8083-exec-2] INFO com.ai.mock.rests.Demo -age=3

<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object… uriVariables)

    /*client*/
    @Test
    public void testRest3(){
        RestTemplate restTemplate = new RestTemplate();
        String getUrl = "http://localhost:8083/mock/test/get3?name={name}";
        String name = "hello world";
        ResponseEntity<Student> entity = restTemplate.getForEntity(getUrl,Student.class,name);
        Student s = entity.getBody();
        log.info(s.getName());
        log.info(entity.toString());
        log.info(entity.getHeaders().toString());
        log.info(entity.getBody().toString());
    }

Client log output:
2020-05-27 09:39:54 [main] info apptest – < 200, student (name = Wang Jie, age = 28), [content type: “application / JSON”, transfer encoding: “chunked”, date: “wed, 27 May 2020 01:39:54 GMT”, keep alive: “timeout = 60”, connection: “keep alive”] >
2020-05-27 09:39:54 [main] INFO AppTest -[Content-Type:”application/json”, Transfer-Encoding:”chunked”, Date:”Wed, 27 May 2020 01:39:54 GMT”, Keep-Alive:”timeout=60″, Connection:”keep-alive”]
2020-05-27 09:39:54 [main] info apptest – student (name = Wang Jie, age = 28)

/*server*/
    @GetMapping("/test/get3")
    public JSONObject get3(@RequestParam("name") String username){
        Log.debug ("get server called");
        log.info(username);
        JSONObject result = new JSONObject();
        Result.put ("name", "Wang Jie");
        result.put("age",28);
        return result;
    }

Server log output:
2020-05-27 09:39:54 [http-nio-8083-exec-10] debug com.ai.mock.resets.demo – get server called
2020-05-27 09:39:54 [http-nio-8083-exec-10] INFO com.ai.mock.rests.Demo -hello world
If the object is a Java object, it doesn’t work if you want to pass parameters like a map! I want to make complaints about it. If you want to pass Java objects, you have to pass them like this:

/*client*/
    @Test
    public void testRest4(){
        RestTemplate restTemplate = new RestTemplate();
        String getUrl = "http://localhost:8083/mock/test/get4?name={student}";
        Student student = new student ("skin shrimp", 3);
        ResponseEntity<Student> entity = restTemplate.getForEntity(getUrl,Student.class,student);
        log.info(entity.toString());
        log.info(entity.getHeaders().toString());
        log.info(entity.getBody().toString());
    }

Client log output:
2020-05-27 09:48:35 [main] info apptest – < 200, student (name = Wang Jie, age = 28), [content type: “application / JSON”, transfer encoding: “chunked”, date: “wed, 27 May 2020 01:48:34 GMT”, keep alive: “timeout = 60”, connection: “keep alive”] >
2020-05-27 09:48:35 [main] INFO AppTest -[Content-Type:”application/json”, Transfer-Encoding:”chunked”, Date:”Wed, 27 May 2020 01:48:34 GMT”, Keep-Alive:”timeout=60″, Connection:”keep-alive”]
2020-05-27 09:48:35 [main] info apptest – student (name = Wang Jie, age = 28)

/*server*/
    @GetMapping("/test/get4")
    public JSONObject get4(@RequestParam("name") String name){
        Log.debug ("get server called");
        log.info(name);
        JSONObject result = new JSONObject();
        Result.put ("name", "Wang Jie");
        result.put("age",28);
        return result;
    }

Server log output:
2020-05-27 09:48:34 [http-nio-8083-exec-5] debug com.ai.mock.resets.demo – get server called
2020-05-27 09:48:34 [http-nio-8083-exec-5] info com.ai.mock.rests.demo – student (name = shrimp, age = 3)

<T> T getForObject(URI url, Class<T> responseType)

/*client*/
    @Test
    public void testRest5(){
        RestTemplate restTemplate = new RestTemplate();
        String getUrl = "http://localhost:8083/mock/test/get5/helloworld";
        Student stu = restTemplate.getForObject(getUrl,Student.class);
        log.info(stu.toString());
    }

Client output log:
2020-05-27 10:10:52 [main] info apptest – student (name = Wang Jie, age = 28)

/*server*/
    @GetMapping("/test/get5/{name}")
    public JSONObject get5(@PathVariable("name") String username){
        Log.debug ("get server called");
        log.info(username);
        JSONObject result = new JSONObject();
        Result.put ("name", "Wang Jie");
        result.put("age",28);
        return result;
    }

Server output log:
2020-05-27 10:10:52 [http-nio-8083-exec-1] debug com.ai.mock.resets.demo – get server called
2020-05-27 10:10:52 [http-nio-8083-exec-1] INFO com.ai.mock.rests.Demo -helloworld

/*client*/
    @Test
    public void testRest6(){
        RestTemplate restTemplate = new RestTemplate();
        String getUrl = "http://localhost:8083/mock/test/get6?name={name}&age={age}";
        Map<String,Object> map = new HashMap<>();
        Map.put ("name", "skin shrimp");
        map.put("age",3);
        Student s = restTemplate.getForObject(getUrl,Student.class,map);
        log.info(s.toString());
    }

Client output log:
2020-05-27 10:14:47 [main] info apptest – student (name = Wang Jie, age = 28)

/*server*/
    @GetMapping("/test/get6")
    public JSONObject get6(@RequestParam("name") String username,@RequestParam("age") Integer age){
        Log.debug ("get server called");
        log.info("username=" + username);
        log.info("age=" + age);
        JSONObject result = new JSONObject();
        Result.put ("name", "Wang Jie");
        result.put("age",28);
        return result;
    }

Server output log:
2020-05-27 10:14:47 [http-nio-8083-exec-2] debug com.ai.mock.resets.demo – get server called
2020-05-27 10:14:47 [http-nio-8083-exec-2] info com.ai.mock.resets.demo – username = shrimp
2020-05-27 10:14:47 [http-nio-8083-exec-2] INFO com.ai.mock.rests.Demo -age=3

<T> T getForObject(String url, Class<T> responseType, Object… uriVariables)

/*client*/
    @Test
    public void testRest7(){
        RestTemplate restTemplate = new RestTemplate();
        String getUrl = "http://localhost:8083/mock/test/get7?name={stu}";
        Student stu = new student ("skin shrimp", 3);
        Student s = restTemplate.getForObject(getUrl,Student.class,stu);
        log.info(s.toString());
    }

Client log output:
2020-05-27 10:22:29 [main] info apptest – student (name = Wang Jie, age = 28)

/*server*/
    @GetMapping("/test/get7")
    public JSONObject get7(@RequestParam("name") String name){
        Log.debug ("get server called");
        log.info(name);
        JSONObject result = new JSONObject();
        Result.put ("name", "Wang Jie");
        result.put("age",28);
        return result;
    }

Server log output:
2020-05-27 10:25:50 [http-nio-8083-exec-3] debug com.ai.mock.resets.demo – get server called
2020-05-27 10:25:50 [http-nio-8083-exec-3] info com.ai.mock.rests.demo – student (name = shrimp, age = 3)

Get summary

After looking at the pile of test code in front, I can’t help asking: Why are you so lipstick? Won’t the server use jsonobject to accept map or Java objects?
The answer is: no! The idea of the designer is to get the parameters from the URL. Whether you are from the path or the URL parameter. You can’t take it from the body.
The difference between getforentity and getforebject is that the data returned by getforentity contains the request header and request body, while getforebject only contains the request body.

Send post request

There are two main post submission methods: form submission and payload submission.
Here is my humble opinion:

  • Form submission: content type: application / x-www-form-urlencoded in the request header, whether it is a request sent by the back-end personnel through resttemplate or the front-end personnel through Ajax; charset=UTF-8。 The server side needs to use requestparmas to obtain parameter values, which cannot be obtained using requestbody.
  • Payload submission: whether the request is sent by the back-end through resttemplate or the front-end personnel through Ajax, the content type in the request header is: application / JSON; charset=UTF-8。 The server side needs to use requestbody to obtain parameter values, which cannot be obtained using requestparams.

<T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType)

<T> Responseentity < T > postforentity (URI URL, @ nullable object request, class < T > responsetype) form submission

/*client*/
    /*The form data server for form submission can only use requestparams value, not requestbody*/
    /*Content-Type: application/x-www-form-urlencoded; charset=UTF-8*/
    @Test
    public void testRest8(){
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8083/mock/test/post";
        MultiValueMap params = new LinkedMultiValueMap();
        Params. Add ("name", "skin shrimp");
        params.add("age",3);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap> entity = new HttpEntity<>(params,headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,entity,String.class);
        log.info(responseEntity.getBody());
    }

Client log:
2020-05-28 16:06:54 [main] info apptest -{“name”: “Wang Jie”, “age”: 28}

/*server*/
    @PostMapping("/test/post")
    public JSONObject post(@RequestParam("name") String name,@RequestParam("age") Integer age){
        Log.debug ("post server is called");
        log.info(name);
        log.info(age.toString());
        JSONObject result = new JSONObject();
        Result.put ("name", "Wang Jie");
        result.put("age",28);
        return result;
    }

Server log:
2020-05-28 16:06:54 [http-nio-8083-exec-4] debug com.ai.mock.resets.demo – post server called
2020-05-28 16:06:54 [http-nio-8083-exec-4] info com.ai.mock.rests.demo – skin shrimp
2020-05-28 16:06:54 [http-nio-8083-exec-4] INFO com.ai.mock.rests.Demo -3

<T> Responseentity < T > postforentity (URI URL, @ nullable object request, class < T > responsetype) payload submission

/*<T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType)*/
    /*Payload submission*/
    /*The parameter is placed in body requestparams, but it cannot be obtained*/
    /*Content-Type: application/json;charset=UTF-8*/
    @Test
    public void testRest9(){
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8083/mock/test/post2";
        MultiValueMap params = new LinkedMultiValueMap();
        Params. Add ("name", "skin shrimp");
        params.add("age",3);
        /*The code block unregistered here can also be passed as a request body parameter*/
        /*Map<String,Object> params = new HashMap<>();
        Params.put ("name", "skin shrimp");
        params.put("age",3);*/
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<Map> entity = new HttpEntity<>(params,headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,entity,String.class);
        log.info(responseEntity.getBody());
    }

Client log:
2020-05-28 16:12:35 [main] info apptest -{“name”: “Wang Jie”, “age”: 28}

/*server*/
    @PostMapping("/test/post2")
    public JSONObject post2(@RequestBody JSONObject jsonObject){
        Log.debug ("post server is called");
        log.info(jsonObject.toJSONString());
        JSONObject result = new JSONObject();
        Result.put ("name", "Wang Jie");
        result.put("age",28);
        return result;
    }

Server log:
2020-05-28 16:12:35 [http-nio-8083-exec-6] debug com.ai.mock.resets.demo – post server called
2020-05-28 16:12:35 [http-nio-8083-exec-6] info com.ai.mock.resets.demo – {“name”: [“skin shrimp”], “age”: [3]}

<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)

Here is an example based on payload mode or form data mode.

/*In addition to passing values in the request header, you can also pass values in the request parameters. You need to display the declaration. The request body is used to obtain the request header, and requestparam is used to obtain the request header*/
    @Test
    public void testRest10(){
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8083/mock/test/post3?sex={sex}";
        MultiValueMap params = new LinkedMultiValueMap();
        Params. Add ("name", "skin shrimp");
        params.add("age",3);
        Map<String,Object> uriParam = new HashMap<>();
        uriParam.put("sex","man");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<Map> entity = new HttpEntity<>(params,headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,entity,String.class,uriParam);
        log.info(responseEntity.getBody());
    }

Client log:
2020-05-28 16:18:32 [main] info apptest -{“name”: “Wang Jie”, “age”: 28}

@PostMapping("/test/post3")
    public JSONObject post2(@RequestBody JSONObject jsonObject,@RequestParam("sex") String sex){
        Log.debug ("post server is called");
        log.info(jsonObject.toJSONString());
        log.info(sex);
        JSONObject result = new JSONObject();
        Result.put ("name", "Wang Jie");
        result.put("age",28);
        return result;
    }

Server side log:
2020-05-28 16:18:32 [http-nio-8083-exec-7] debug com.ai.mock.resets.demo – post server called
2020-05-28 16:18:32 [http-nio-8083-exec-7] info com.ai.mock.resets.demo – {“name”: [“skin shrimp”], “age”: [3]}
2020-05-28 16:18:32 [http-nio-8083-exec-7] INFO com.ai.mock.rests.Demo -man

<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Object… uriVariables)

Here is an example based on payload mode or form data mode.

@Test
    public void testRest11(){
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8083/mock/test/post4?stu={stu}";
        MultiValueMap params = new LinkedMultiValueMap();
        Params. Add ("name", "skin shrimp");
        params.add("age",3);
        Student stu = new student ("Wang Jie", 20);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<Map> entity = new HttpEntity<>(params,headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,entity,String.class,stu);
        log.info(responseEntity.getBody());
    }

Client log:
2020-05-28 16:22:16 [main] info apptest -{“name”: “Wang Jie”, “age”: 28}

@PostMapping("/test/post4")
    public JSONObject post4(@RequestBody JSONObject jsonObject,@RequestParam("stu") String stu){
        Log.debug ("post server is called");
        log.info(jsonObject.toJSONString());
        log.info(stu);
        JSONObject result = new JSONObject();
        Result.put ("name", "Wang Jie");
        result.put("age",28);
        return result;
    }

Server log:
2020-05-28 16:22:16 [http-nio-8083-exec-10] debug com.ai.mock.resets.demo – post server called
2020-05-28 16:22:16 [http-nio-8083-exec-10] info com.ai.mock.resets.demo – {“name”: [“skin shrimp”], “age”: [3]}
2020-05-28 16:22:16 [http-nio-8083-exec-10] info com.ai.mock.rests.demo – student (name = Wang Jie, age = 20)
Postforentity summary: if it is a form data request, you need to set the contenttype of the request header to mediatype.application_ JSON_ Utf8 and putting parameters into multivaluemap can not use ordinary map. At the same time, it is necessary to put the request body request header into httpentity to initiate the request. The server accepts parameters using requestparam.
If it is a payload request, a normal map can also be used. You need to set cententtype to mediatype.application_ JSON_ UTF8。 The server accepts parameters and uses reuqestbody

<T> T postForObject(URI url, @Nullable Object request, Class<T> responseType)

/*Default payload mode*/
    @Test
    public void testRest12(){
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8083/mock/test/post2";
        Map<String,Object> params = new HashMap<>();
        Params.put ("name", "skin shrimp");
        params.put("age",3);
        String result = restTemplate.postForObject(url,params,String.class);
        log.info(result);
    }

Client log:
2020-05-28 16:26:08 [main] info apptest -{“name”: “Wang Jie”, “age”: 28}

@PostMapping("/test/post2")
    public JSONObject post2(@RequestBody JSONObject jsonObject){
        Log.debug ("post server is called");
        log.info(jsonObject.toJSONString());
        JSONObject result = new JSONObject();
        Result.put ("name", "Wang Jie");
        result.put("age",28);
        return result;
    }

Server log:
2020-05-28 16:26:08 [http-nio-8083-exec-2] debug com.ai.mock.resets.demo – post server called
2020-05-28 16:26:08 [http-nio-8083-exec-2] info com.ai.mock.resets.demo – {“name”: “skin shrimp”, “age”: 3}

<T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)

@Test
    public void testRest13(){
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8083/mock/test/post3?sex={sex}";
        Map<String,Object> params = new HashMap<>();
        Params.put ("name", "skin shrimp");
        params.put("age",3);
        Map<String,Object> uriParam = new HashMap<>();
        uriParam.put("sex","man");
        String result = restTemplate.postForObject(url,params,String.class,uriParam);
        log.info(result);
    }

Client log:
2020-05-28 16:28:51 [main] info apptest -{“name”: “Wang Jie”, “age”: 28}

@PostMapping("/test/post3")
    public JSONObject post2(@RequestBody JSONObject jsonObject,@RequestParam("sex") String sex){
        Log.debug ("post server is called");
        log.info(jsonObject.toJSONString());
        log.info(sex);
        JSONObject result = new JSONObject();
        Result.put ("name", "Wang Jie");
        result.put("age",28);
        return result;
    }

Server log:
2020-05-28 16:28:51 [http-nio-8083-exec-4] debug com.ai.mock.resets.demo – post server called
2020-05-28 16:28:51 [http-nio-8083-exec-4] info com.ai.mock.resets.demo – {“name”: “skin shrimp”, “age”: 3}
2020-05-28 16:28:51 [http-nio-8083-exec-4] INFO com.ai.mock.rests.Demo -man

<T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object… uriVariables)

@Test
    public void testRest14(){
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8083/mock/test/post4?stu={stu}";
        Map<String,Object> params = new HashMap<>();
        Params.put ("name", "skin shrimp");
        params.put("age",3);
        Student stu = new student ("Wang Jie", 20);
        String result = restTemplate.postForObject(url,params,String.class,stu);
        log.info(result);
    }

Client log:
2020-05-28 16:29:42 [main] info apptest -{“name”: “Wang Jie”, “age”: 28}

@PostMapping("/test/post4")
    public JSONObject post4(@RequestBody JSONObject jsonObject,@RequestParam("stu") String stu){
        Log.debug ("post server is called");
        log.info(jsonObject.toJSONString());
        log.info(stu);
        JSONObject result = new JSONObject();
        Result.put ("name", "Wang Jie");
        result.put("age",28);
        return result;
    }

Server log:
2020-05-28 16:29:42 [http-nio-8083-exec-6] debug com.ai.mock.resets.demo – post server called
2020-05-28 16:29:42 [http-nio-8083-exec-6] info com.ai.mock.resets.demo – {“name”: “skin shrimp”, “age”: 3}
2020-05-28 16:29:42 [http-nio-8083-exec-6] info com.ai.mock.rests.demo – student (name = Wang Jie, age = 20)

exchange

As for exchange, if you know the above usage, you only need to add an httpmethod to the parameter request method. No more details.