What is the restTemplate.exchange() method for?

自作多情 提交于 2019-12-20 11:07:53

问题


Actually what does the restTemplate.exchange() method do?

@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());
}

回答1:


The method documentation is pretty straightforward:

Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the response as ResponseEntity.

URI Template variables are expanded using the given 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:

  • A GET request will be performed to the given URL sending the HTTP headers that are wrapped in the HttpEntity instance.
  • The given URL contains a template variable ({id}). It will be replaced with the value given in the last method parameter (id).
  • The response entity will be returned​ as a byte[] wrapped into a ResponseEntity instance.



回答2:


The more generic exchange API requires a HttpMethod parameter and a request object for completeness. Compare:

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

ResponseEntity<Foo> response = 
restTemplate.getForEntity(url, Foo.class);



回答3:


The exchange method executes the HTTP method against the specified URI template, passing in the parameters for replacement. In this case it gets an image for a person entity for its Id parameter and returns the byte array for it.



来源:https://stackoverflow.com/questions/20186497/what-is-the-resttemplate-exchange-method-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!