restTemplate請求GET


public String hello() {
        StringBuilder result = new StringBuilder();

// GET
//方式一
        result.append(restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class).getBody()).append("<br>");
//方式二
        result.append(restTemplate.getForEntity("http://HELLO-SERVICE/hello1?name={1}", String.class, "didi").getBody()).append("<br>");
//方式三
        Map<String, String> params = new HashMap<>();
        params.put("name", "dada");
        result.append(restTemplate.getForEntity("http://HELLO-SERVICE/hello1?name={name}", String.class, params).getBody()).append("<br>");
//方式四
        UriComponents uriComponents = UriComponentsBuilder.fromUriString(
                "http://HELLO-SERVICE/hello1?name={name}")
                .build()
                .expand("dodo")
                .encode();
        URI uri = uriComponents.toUri();
        result.append(restTemplate.getForEntity(uri, String.class).getBody()).append("<br>");
    }

 

getForEntity | postForEntity

getForEntity方法的返回值是一個ResponseEntity<T>,ResponseEntity<T>是Spring對HTTP請求響應的封裝,包括了幾個重要的元素,如響應碼、contentType、contentLength、響應消息體等

第一個參數為請求地址

第二個參數String.class表示我希望返回的body類型是String

可以用一個數字做占位符,最后是一個可變長度的參數,來一一替換前面的占位符
也可以前面使用name={name}這種形式,最后一個參數是一個map,map的key即為前邊占位符的名字,map的value為參數值

getForObject | postForObject

函數實際上是對getForEntity函數的進一步封裝,如果你只關注返回的消息體的內容,對其他信息都不關注,此時可以使用getForObject,

 

 


免責聲明!

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



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