关于rest:restTemplate.exchange()方法有什么作用?

What is the restTemplate.exchange() method for?

实际上,restTemplate.exchange()方法有什么作用?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@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());
}

方法文档非常简单:

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.

考虑从您自己的问题中提取的以下代码:

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

我们有以下内容:

  • 将对给定的URL执行GET请求,以发送包装在HttpEntity实例中的HTTP标头。
  • 给定的URL包含模板变量({id})。它会被最后一个方法参数(id)中给定的值替换。
  • 响应实体将被返回?作为包装在ResponseEntity实例中的byte[]


TL; DR:问:所谓的请求-响应对是什么?答:"交换"。

几乎在偶然的情况下,HTTP的官方技术文档中使用了术语"交换"来指代HTTP请求和相应的响应。

但是,看看以下问题的答案,很显然,尽管对于某些人来说,这可能代表了事实上的标准,但其他许多人却没有意识到,或者没有采用它。

  • 请求-响应对叫什么?
  • HTTP请求+响应的名称

该文档没有费心提及名称的词源-可能假设它是显而易见的。

但是请注意,这里列出了许多不同的RestTemplate HTTP请求方法,其中只有一小部分被命名为exchange。该列表主要由特定于HTTP方法的名称组成,例如deleteputgetForEntitypostForObject等。从技术上讲,所有这些方法都以相同的意义执行交换,但是更加集中的便捷方法仅限于可能的交换功能和参数+返回类型的特定子集。

简而言之,exchange函数集是RestTemplate提供的最通用/功能最多的方法,因此,当其他任何方法都不提供足以满足您需要的参数集时,可以使用exchange

例如:

  • 使用restTemplate发送带有身份验证标头的GET请求,其中OP注意到" ...发送标头(如接受和授权)的唯一方法是使用交换方法..."

更为通用的交换API需要HttpMethod参数和一个请求对象以确保完整性。相比:

1
2
3
4
5
ResponseEntity<Foo> response =
restTemplate.exchange(url, HttpMethod.GET, request, Foo.class);

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

exchange方法对指定的URI模板执行HTTP方法,并传入替换参数。在这种情况下,它会为其ID参数获取人物实体的图像,并为其返回字节数组。