sne*_*eha 25 rest resttemplate
实际上这个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());
}
Run Code Online (Sandbox Code Playgroud)
cas*_*lin 19
该方法的文档是非常简单的:
对给定的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);
Run Code Online (Sandbox Code Playgroud)
我们有以下内容:
GET
请求将被执行以给定的URL发送符合包裹在HTTP头HttpEntity
实例.{id}
),因此它将替换为最后一个方法参数(id
)中给出的值.byte[]
包装返回ResponseEntity
实例返回.TL;DR:问: 请求-响应对叫什么? 答:一个“交换”。
在HTTP 的官方技术文档中,几乎偶然地使用术语交换来指代结合相应响应的 HTTP 请求。
然而,看看以下问题的答案,很明显,虽然这对某些人来说可能代表了事实上的标准,但许多其他人并不知道或没有采用它。
该文档没有费心提及名称的词源——可能假设它很明显。
但是请注意,列出了许多不同的 RestTemplate HTTP 请求方法,其中只有一小部分被命名为exchange。列表主要由高达方法HTTP特异性的名字,如delete
,put
,getForEntity
,postForObject
,等等。从技术上讲,所有这些方法都在相同的意义上执行交换,但更集中的便利方法仅限于可能的交换功能和参数+返回类型的特定子集。
简单来说,函数集exchange
是 提供的最通用/最有能力的方法RestTemplate
,所以exchange
当其他方法都没有提供足够完整的参数集来满足您的需求时,您可以使用。
例如:
归档时间: |
|
查看次数: |
63482 次 |
最近记录: |