What is the restTemplate.exchange () method for?

Actually, what does the restTemplate.exchange() method 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()); } 
+18
rest resttemplate
source share
3 answers

The method documentation is pretty simple:

Execute the HTTP method for this URI pattern by writing this request object to the request and returning the response as ResponseEntity .

URI template variables are expanded using the specified URI variables, if any.


Consider the following code extracted from your own question:

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

We have the following:

  • GET request will be executed to the specified URL by sending HTTP headers enclosed in an instance of HttpEntity .
  • This URL contains a template variable ( {id} ). It will be replaced by the value specified in the last parameter of the method ( id ).
  • ResponseEntity object will be returned as a byte[] enclosed in a ResponseEntity instance.
+15
source share

The exchange method executes the HTTP method against the specified URI pattern, passing parameters for replacement. In this case, it receives an image for the user object for its Id parameter and returns an array of bytes for it.

0
source share

For a more general exchange API, the HttpMethod parameter and a request object for completeness are required. For comparison:

 ResponseEntity<Foo> response = restTemplate.exchange(url, HttpMethod.GET, request, Foo.class); ResponseEntity<Foo> response = restTemplate.getForEntity(url, Foo.class); 
0
source share

All Articles