restTemplate.exchange() 方法有什么用? [英] What is the restTemplate.exchange() method for?

查看:137
本文介绍了restTemplate.exchange() 方法有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

restTemplate.exchange() 方法实际上是做什么的?

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

推荐答案

方法文档非常简单:

对给定的URI模板执行HTTP方法,将给定的请求实体写入请求,返回响应为ResponseEntity.

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

使用给定的 URI 变量扩展 URI 模板变量(如果有).

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);

我们有以下几点:

  • GET 请求将是对给定的 URL 执行发送包含在 HttpEntity 实例.
  • 给定的 URL 包含一个模板变量 ({id}).它将被替换为最后一个方法参数 (id) 中给出的值.
  • 响应实体将作为 byte[] 包装到 ResponseEntity 实例.
  • 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.

这篇关于restTemplate.exchange() 方法有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆