Spring RestTemplate 之get請求


一,簡介:Spring RestTemplate 是 Spring 提供的用於訪問 Rest 服務的客戶端,RestTemplate 提供了多種便捷訪問遠程Http服務的方法,能夠大大提高客戶端的編寫效率

二、RestTemplate中幾種常見請求方法的使用

    ●get請求:在RestTemplate中,發送一個GET請求,我們可以通過如下兩種方式

         第一種:getForEntity

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

 

@Controller

@RequestMapping("/restTest")

public class RestTempLateTest {

private RestTemplate restTemplate = new RestTemplate();

@RequestMapping("/hello")

@ResponseBody

public String getHello() {

// ResponseEntity<IntMonitor> res = restTemplate.getForEntity(url,

// IntMonitor)

ResponseEntity<String> res = restTemplate.getForEntity(

"http://10.145.198.143:8081/ords/data_service/monitor/IntMonitor",

String.class);

String body = res.getBody();

return body;

}

}

        有時候我在調用服務提供者提供的接口時,可能需要傳遞參數,有兩種不同的方式,如下        

        @RequestMapping("/hello1/{flag}")

@ResponseBody

public String getHello1(@PathVariable String flag){

ResponseEntity<String> res = restTemplate.getForEntity(

"http://10.145.198.143:8081/ords/data_service/monitor/IntMonitor/{1}", 

String.class, 

"1");

String body = res.getBody();

return body;

}

 

        @RequestMapping("/hello2/{flag}")

@ResponseBody

public String getHello2(@PathVariable String flag){

Map<String, Object> map = new HashMap<String, Object>();

map.put("flag", flag);

ResponseEntity<String> res = restTemplate.getForEntity(

"http://10.145.198.143:8081/ords/data_service/monitor/IntMonitor/{flag}", 

String.class, 

map);

String body = res.getBody();

return body;

}

    

        @RequestMapping("/hello3/{flag}")

@ResponseBody

public String getHello3(@PathVariable String flag) {

UriComponents uriComponents = UriComponentsBuilder

.fromUriString(

"http://10.145.198.143:8081/ords/data_service/monitor/IntMonitor/{flag}")

.build().expand(flag);

URI uri = uriComponents.toUri();

ResponseEntity<String>  res = restTemplate.getForEntity(uri, String.class);

String body = res.getBody();

return body;

}

  • 可以用一個數字做占位符,最后是一個可變長度的參數,來一一替換前面的占位符

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

  • 調用地址也可以是一個url,而不是一個字符串,這樣可以直接調用url.

        第二種:getForObject

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

            舉一個簡單的例子,如下:

        @RequestMapping("/hello4/{flag}")

@ResponseBody

public String getHello4(@PathVariable String flag) {

UriComponents uriComponents = UriComponentsBuilder

.fromUriString(

"http://10.145.198.143:8081/ords/data_service/monitor/IntMonitor/{flag}")

.build().expand(flag);

URI uri = uriComponents.toUri();

String  res = restTemplate.getForObject(uri, String.class);

return res;

}


免責聲明!

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



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