实际上,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());
}
发布于 2017-02-16 18:55:49
method documentation非常简单:
对给定的URI模板执行HTTP方法,将给定的请求实体写入请求,并将响应作为
ResponseEntity
返回。
URI模板变量使用给定的URI变量进行扩展。
考虑从您自己的问题中提取的以下代码:
ResponseEntity<byte[]> result =
restTemplate.exchange("http://localhost:7070/spring-rest-provider/krams/person/{id}",
HttpMethod.GET, entity, byte[].class, id);
我们有以下内容:
GET
请求,发送包装在HttpEntity
实例中的HTTP头。{id}
)。它将替换为最后一个方法参数中给出的值(id
).ResponseEntity
实例中的byte[]
返回。发布于 2020-04-12 08:36:50
TL;DR:Q: What is a request-response pair called? A: An "exchange“。
在the official technical documentation of HTTP中,术语交换几乎是偶然使用的,指的是与相应响应组合的超文本传输协议请求。
然而,看看以下问题的答案,很明显,虽然这可能代表了一些人的事实标准,但许多其他人没有意识到它,或者没有采用它。
documentation没有提到这个名字的词源--可能假设它是显而易见的。
但是,请注意,这里列出了许多不同的exchange请求方法,并且只有一小部分方法被命名为RestTemplate。该列表主要由-specific名称组成,如delete
、put
、getForEntity
、postForObject
等。从技术上讲,所有这些方法都以相同的意义执行交换,但更集中的便利方法仅限于可能的交换功能和parameter+return类型的特定子集。
简单地说,exchange
RestTemplate
,提供的函数集是最通用/功能最强大的方法,因此当其他方法都没有提供足够完整的参数集来满足您的需求时,您可以使用exchange
。
例如:
发布于 2018-12-17 16:36:22
更通用的exchange API需要一个HttpMethod参数和一个请求对象来保证完整性。比较:
ResponseEntity<Foo> response =
restTemplate.exchange(url, HttpMethod.GET, request, Foo.class);
ResponseEntity<Foo> response =
restTemplate.getForEntity(url, Foo.class);
https://stackoverflow.com/questions/20186497
复制相似问题