一直在用restTemplate?你是否真搞清楚了?


發送GET請求

ResponseEntity getForEntity(URI var1, Class 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());
}

客戶端輸出日志:
2020-05-27 09:14:44 [main] INFO AppTest -<200,Student(name=王傑, 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=王傑, age=28)

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

    @GetMapping("/test/get/{name}")
    public JSONObject get(@PathVariable("name") String username){
        log.debug("get server被調用");
        log.info(username);
        JSONObject result = new JSONObject();
        result.put("name","王傑");
        result.put("age",28);
        return result;
    }
}

服務端輸出日志:
2020-05-27 09:14:44 [http-nio-8083-exec-3] DEBUG com.ai.mock.rests.Demo -get server被調用
2020-05-27 09:14:44 [http-nio-8083-exec-3] INFO com.ai.mock.rests.Demo -helloworld

ResponseEntity getForEntity(String url, Class 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","皮皮蝦");
    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());
    /*驗證entity中放的就是Student對象*/
    Student s = entity.getBody();
    log.info(s.getName());
    log.info(s.getAge().toString());
}

客戶端輸出日志:
2020-05-27 09:26:34 [main] INFO AppTest -<200,Student(name=王傑, 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=王傑, age=28)
2020-05-27 09:26:34 [main] INFO AppTest -王傑
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被調用");
    log.info("username=" + username);
    log.info("age=" + age);
    JSONObject result = new JSONObject();
    result.put("name","王傑");
    result.put("age",28);
    return result;
}

服務端輸出日志:
2020-05-27 09:26:34 [http-nio-8083-exec-2] DEBUG com.ai.mock.rests.Demo -get server被調用
2020-05-27 09:26:34 [http-nio-8083-exec-2] INFO com.ai.mock.rests.Demo -username=皮皮蝦
2020-05-27 09:26:34 [http-nio-8083-exec-2] INFO com.ai.mock.rests.Demo -age=3

ResponseEntity getForEntity(String url, Class 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());
    }

客戶端日志輸出:
2020-05-27 09:39:54 [main] INFO AppTest -<200,Student(name=王傑, 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=王傑, age=28)

    /*server*/
    @GetMapping("/test/get3")
    public JSONObject get3(@RequestParam("name") String username){
        log.debug("get server被調用");
        log.info(username);
        JSONObject result = new JSONObject();
        result.put("name","王傑");
        result.put("age",28);
        return result;
    }

服務端日志輸出:
2020-05-27 09:39:54 [http-nio-8083-exec-10] DEBUG com.ai.mock.rests.Demo -get server被調用
2020-05-27 09:39:54 [http-nio-8083-exec-10] INFO com.ai.mock.rests.Demo -hello world
如果Object為一個java對象,想像Map一樣傳參,行不通!在這里我特么想極力吐槽一波。如果想傳java對象,得這樣傳:

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

客戶端日志輸出:
2020-05-27 09:48:35 [main] INFO AppTest -<200,Student(name=王傑, 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=王傑, age=28)

    /*server*/
    @GetMapping("/test/get4")
    public JSONObject get4(@RequestParam("name") String name){
        log.debug("get server被調用");
        log.info(name);
        JSONObject result = new JSONObject();
        result.put("name","王傑");
        result.put("age",28);
        return result;
    }

服務端日志輸出:
2020-05-27 09:48:34 [http-nio-8083-exec-5] DEBUG com.ai.mock.rests.Demo -get server被調用
2020-05-27 09:48:34 [http-nio-8083-exec-5] INFO com.ai.mock.rests.Demo -Student(name=皮皮蝦, age=3)

T getForObject(URI url, Class 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());
    }

客戶端輸出日志:
2020-05-27 10:10:52 [main] INFO AppTest -Student(name=王傑, age=28)

/*server*/
    @GetMapping("/test/get5/{name}")
    public JSONObject get5(@PathVariable("name") String username){
        log.debug("get server被調用");
        log.info(username);
        JSONObject result = new JSONObject();
        result.put("name","王傑");
        result.put("age",28);
        return result;
    }

服務端輸出日志:
2020-05-27 10:10:52 [http-nio-8083-exec-1] DEBUG com.ai.mock.rests.Demo -get server被調用
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","皮皮蝦");
        map.put("age",3);
        Student s = restTemplate.getForObject(getUrl,Student.class,map);
        log.info(s.toString());
    }

客戶端輸出日志:
2020-05-27 10:14:47 [main] INFO AppTest -Student(name=王傑, age=28)

/*server*/
    @GetMapping("/test/get6")
    public JSONObject get6(@RequestParam("name") String username,@RequestParam("age") Integer age){
        log.debug("get server被調用");
        log.info("username=" + username);
        log.info("age=" + age);
        JSONObject result = new JSONObject();
        result.put("name","王傑");
        result.put("age",28);
        return result;
    }

服務端輸出日志:
2020-05-27 10:14:47 [http-nio-8083-exec-2] DEBUG com.ai.mock.rests.Demo -get server被調用
2020-05-27 10:14:47 [http-nio-8083-exec-2] INFO com.ai.mock.rests.Demo -username=皮皮蝦
2020-05-27 10:14:47 [http-nio-8083-exec-2] INFO com.ai.mock.rests.Demo -age=3

T getForObject(String url, Class 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("皮皮蝦",3);
        Student s = restTemplate.getForObject(getUrl,Student.class,stu);
        log.info(s.toString());
    }

客戶端日志輸出:
2020-05-27 10:22:29 [main] INFO AppTest -Student(name=王傑, age=28)

/*server*/
    @GetMapping("/test/get7")
    public JSONObject get7(@RequestParam("name") String name){
        log.debug("get server被調用");
        log.info(name);
        JSONObject result = new JSONObject();
        result.put("name","王傑");
        result.put("age",28);
        return result;
    }

服務端日志輸出:
2020-05-27 10:25:50 [http-nio-8083-exec-3] DEBUG com.ai.mock.rests.Demo -get server被調用
2020-05-27 10:25:50 [http-nio-8083-exec-3] INFO com.ai.mock.rests.Demo -Student(name=皮皮蝦, age=3)

GET小結

看了前面的一堆測試代碼,不禁提問:你怎么這么唇筆啊?server端不會用JSONObject來接受MAP 或者 java對象嗎?
答案是:不可以!特么的設計者的思想就是GET方式 傳參 就從URL里面取值。不管你是從path還是從url參數里面都可以。就是不可以從body里面取。
getForEntity與getForObject的區別是 getForEntity返回的數據中包含了請求頭、請求體,而getForObject只有體。

發送POST請求

POST提交方式主要有兩種:form表單提交、payload提交。
這里給出鄙人的一點淺薄的見解:

  • form表單提交:無論是后端通過restTemplate還是前端人員通過ajax發送的請求,請求頭中Content-Type: application/x-www-form-urlencoded; charset=UTF-8。server端獲取參數值,需要使用RequestParmas,不能使用RequestBody獲取到。
  • payload提交:無論是后端通過restTemplate還是前端人員通過ajax發送的請求,請求頭中Content-Type: application/json;charset=UTF-8。server端獲取參數值,需要使用RequestBody,不能使用RequestParams獲取到。

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

ResponseEntity postForEntity(URI url, @Nullable Object request, Class responseType) form提交

    /*client*/
    /*表單提交 Form Data服務端只能用RequestParams取值 不能用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","皮皮蝦");
        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());
    }

客戶端日志:
2020-05-28 16:06:54 [main] INFO AppTest -{"name":"王傑","age":28}

    /*server*/
    @PostMapping("/test/post")
    public JSONObject post(@RequestParam("name") String name,@RequestParam("age") Integer age){
        log.debug("post server被調用");
        log.info(name);
        log.info(age.toString());
        JSONObject result = new JSONObject();
        result.put("name","王傑");
        result.put("age",28);
        return result;
    }

服務端日志:
2020-05-28 16:06:54 [http-nio-8083-exec-4] DEBUG com.ai.mock.rests.Demo -post server被調用
2020-05-28 16:06:54 [http-nio-8083-exec-4] INFO com.ai.mock.rests.Demo -皮皮蝦
2020-05-28 16:06:54 [http-nio-8083-exec-4] INFO com.ai.mock.rests.Demo -3

ResponseEntity postForEntity(URI url, @Nullable Object request, Class responseType) payload提交

    /*<T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType)*/
    /*payload提交*/
    /*參數放在body requestParams 取不到*/
    /*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","皮皮蝦");
        params.add("age",3);
        /*此處注銷的代碼塊 也可以作為請求體參數傳遞*/
        /*Map<String,Object> params = new HashMap<>();
        params.put("name","皮皮蝦");
        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());
    }

客戶端日志:
2020-05-28 16:12:35 [main] INFO AppTest -{"name":"王傑","age":28}

    /*server*/
    @PostMapping("/test/post2")
    public JSONObject post2(@RequestBody JSONObject jsonObject){
        log.debug("post server被調用");
        log.info(jsonObject.toJSONString());
        JSONObject result = new JSONObject();
        result.put("name","王傑");
        result.put("age",28);
        return result;
    }

服務端日志:
2020-05-28 16:12:35 [http-nio-8083-exec-6] DEBUG com.ai.mock.rests.Demo -post server被調用
2020-05-28 16:12:35 [http-nio-8083-exec-6] INFO com.ai.mock.rests.Demo -{"name":["皮皮蝦"],"age":[3]}

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

這里就基於payload方式舉例子了,也可以基於form data 方式。

    /*除了請求頭里面傳值 還可以在 請求參數里面傳值 需要顯示申明 請求體用RequestBody獲取 請求頭用RequestParam獲取*/
    @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","皮皮蝦");
        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());
    }

客戶端日志:
2020-05-28 16:18:32 [main] INFO AppTest -{"name":"王傑","age":28}

    @PostMapping("/test/post3")
    public JSONObject post2(@RequestBody JSONObject jsonObject,@RequestParam("sex") String sex){
        log.debug("post server被調用");
        log.info(jsonObject.toJSONString());
        log.info(sex);
        JSONObject result = new JSONObject();
        result.put("name","王傑");
        result.put("age",28);
        return result;
    }

server端日志:
2020-05-28 16:18:32 [http-nio-8083-exec-7] DEBUG com.ai.mock.rests.Demo -post server被調用
2020-05-28 16:18:32 [http-nio-8083-exec-7] INFO com.ai.mock.rests.Demo -{"name":["皮皮蝦"],"age":[3]}
2020-05-28 16:18:32 [http-nio-8083-exec-7] INFO com.ai.mock.rests.Demo -man

ResponseEntity postForEntity(String url, @Nullable Object request, Class responseType, Object... uriVariables)

這里就基於payload方式舉例子了,也可以基於form data 方式。

    @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","皮皮蝦");
        params.add("age",3);
        Student stu = new Student("王傑",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());
    }

客戶端日志:
2020-05-28 16:22:16 [main] INFO AppTest -{"name":"王傑","age":28}

    @PostMapping("/test/post4")
    public JSONObject post4(@RequestBody JSONObject jsonObject,@RequestParam("stu") String stu){
        log.debug("post server被調用");
        log.info(jsonObject.toJSONString());
        log.info(stu);
        JSONObject result = new JSONObject();
        result.put("name","王傑");
        result.put("age",28);
        return result;
    }

服務端日志:
2020-05-28 16:22:16 [http-nio-8083-exec-10] DEBUG com.ai.mock.rests.Demo -post server被調用
2020-05-28 16:22:16 [http-nio-8083-exec-10] INFO com.ai.mock.rests.Demo -{"name":["皮皮蝦"],"age":[3]}
2020-05-28 16:22:16 [http-nio-8083-exec-10] INFO com.ai.mock.rests.Demo -Student(name=王傑, age=20)
postForEntity小結:如果是form data請求 需要設置請求頭的ContentType為MediaType.APPLICATION_JSON_UTF8 且將參數 放入MultiValueMap中 不可以使用普通Map,同時需要將請求體 請求頭放入HttpEntity中之后,發起請求。服務端接受參數使用RequestParam。
如果是payload請求 普通Map也可以,需要將CententType設置為MediaType.APPLICATION_JSON_UTF8。服務端接受參數使用ReuqestBody.

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

    /*默認 payload方式*/
    @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","皮皮蝦");
        params.put("age",3);
        String result = restTemplate.postForObject(url,params,String.class);
        log.info(result);
    }

客戶端日志:
2020-05-28 16:26:08 [main] INFO AppTest -{"name":"王傑","age":28}

    @PostMapping("/test/post2")
    public JSONObject post2(@RequestBody JSONObject jsonObject){
        log.debug("post server被調用");
        log.info(jsonObject.toJSONString());
        JSONObject result = new JSONObject();
        result.put("name","王傑");
        result.put("age",28);
        return result;
    }

服務端日志:
2020-05-28 16:26:08 [http-nio-8083-exec-2] DEBUG com.ai.mock.rests.Demo -post server被調用
2020-05-28 16:26:08 [http-nio-8083-exec-2] INFO com.ai.mock.rests.Demo -{"name":"皮皮蝦","age":3}

T postForObject(String url, @Nullable Object request, Class 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","皮皮蝦");
        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);
    }

客戶端日志:
2020-05-28 16:28:51 [main] INFO AppTest -{"name":"王傑","age":28}

    @PostMapping("/test/post3")
    public JSONObject post2(@RequestBody JSONObject jsonObject,@RequestParam("sex") String sex){
        log.debug("post server被調用");
        log.info(jsonObject.toJSONString());
        log.info(sex);
        JSONObject result = new JSONObject();
        result.put("name","王傑");
        result.put("age",28);
        return result;
    }

服務端日志:
2020-05-28 16:28:51 [http-nio-8083-exec-4] DEBUG com.ai.mock.rests.Demo -post server被調用
2020-05-28 16:28:51 [http-nio-8083-exec-4] INFO com.ai.mock.rests.Demo -{"name":"皮皮蝦","age":3}
2020-05-28 16:28:51 [http-nio-8083-exec-4] INFO com.ai.mock.rests.Demo -man

T postForObject(String url, @Nullable Object request, Class 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","皮皮蝦");
        params.put("age",3);
        Student stu = new Student("王傑",20);
        String result = restTemplate.postForObject(url,params,String.class,stu);
        log.info(result);
    }

客戶端日志:
2020-05-28 16:29:42 [main] INFO AppTest -{"name":"王傑","age":28}

    @PostMapping("/test/post4")
    public JSONObject post4(@RequestBody JSONObject jsonObject,@RequestParam("stu") String stu){
        log.debug("post server被調用");
        log.info(jsonObject.toJSONString());
        log.info(stu);
        JSONObject result = new JSONObject();
        result.put("name","王傑");
        result.put("age",28);
        return result;
    }

服務端日志:
2020-05-28 16:29:42 [http-nio-8083-exec-6] DEBUG com.ai.mock.rests.Demo -post server被調用
2020-05-28 16:29:42 [http-nio-8083-exec-6] INFO com.ai.mock.rests.Demo -{"name":"皮皮蝦","age":3}
2020-05-28 16:29:42 [http-nio-8083-exec-6] INFO com.ai.mock.rests.Demo -Student(name=王傑, age=20)

exchange

至於exchange如果知道上面的用法之后 ,只需要在參數請求方法中 添加一個HttpMethod就OK。不再贅述。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM