2013-11-25 71 views
6

其實restTemplate.exchange()方法是做什麼的?什麼是restTemplate.exchange()方法?

@RequestMapping(value = "/getphoto", method = RequestMethod.GET) 
public void getPhoto(@RequestParam("id") Long id, HttpServletResponse response) { 

    logger.debug("Retrieve photo with id: " + id); 

    // Prepare acceptable media type 
    List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>(); 
    acceptableMediaTypes.add(MediaType.IMAGE_JPEG); 

    // Prepare header 
    HttpHeaders headers = new HttpHeaders(); 
    headers.setAccept(acceptableMediaTypes); 
    HttpEntity<String> entity = new HttpEntity<String>(headers); 

    // Send the request as GET 
    ResponseEntity<byte[]> result = 
     restTemplate.exchange("http://localhost:7070/spring-rest-provider/krams/person/{id}", 
           HttpMethod.GET, entity, byte[].class, id); 

    // Display the image 
    Writer.write(response, result.getBody()); 
} 

回答

0

exchange方法針對指定的URI模板執行HTTP方法,傳入參數進行替換。在這種情況下,它爲一個人實體獲取其Id參數的圖像,並返回它的字節數組。

6

method documentation是非常簡單的:

執行的HTTP方法爲給定URI模板,寫入給定請求實體於該請求,並返回響應作爲ResponseEntity

URI模板變量使用給定的URI變量進行擴展(如果有的話)。


Considere從你的問題中提取下面的代碼:

ResponseEntity<byte[]> result = 
    restTemplate.exchange("http://localhost:7070/spring-rest-provider/krams/person/{id}", 
          HttpMethod.GET, entity, byte[].class, id); 

我們有以下幾點:

  • 一個GET請求將發送HTTP標頭進行給定的URL包含在HttpEntity實例中。
  • 由於該URL包含一個模板變量({id}),因此它將替換爲上一個方法參數(id)中給出的值。
  • 響應實體將作爲byte[]返回,幷包裝到ResponseEntity實例中。