一个人至少拥有一个梦想,有一个理由去坚强

心若没有栖息的地方,到哪里都是在流浪

Spring RestTemplate——exchange()方法

后端开发中,需要通过HTTP访问其他网络资源时,常用到Spring 自带的RestTemplate类的exchange()方法。

使用实例如下,方便日后参考。关于具体的方法介绍说明,以后有时间再补充。

查看源码,其中一个exchange的实现如下:

@Override
  public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity,
      ParameterizedTypeReference<T> responseType) throws RestClientException {

    Type type = responseType.getType();
    RequestCallback requestCallback = httpEntityCallback(requestEntity, type);
    ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(type);
    return execute(url, method, requestCallback, responseExtractor);
  }

下面介绍方法参数:

  • URI:访问资源的路径
  • HttpMethod:所要请求的方式。有GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRAC
  • HttpEntity:请求的实体。封装请求头,请求内容
  • ParameterizedTypeReference:响应类型,根据服务接口的返回类型决定

实例:

public class RestTemplateExchange {
    private static final String ARCHIVE_SEND_URL = "http://127.0.0.1:50000/com/demo";
    private static final ParameterizedTypeReference<ResponseData<FileSendVO>> 
            RESPONSE_TYPE = new ParameterizedTypeReference<ResponseData<FileSendVO>>() {};

    @Autowired
    private RestTemplate restTemplate;

   private ResponseData<FileSendVO> manuallySend(SendQuery sendQuery) {
        HttpEntity<String> requestEntry = buildJsonRequestEntity(sendQuery);
        ResponseEntity<ResponseData<FileSendVO>> responseEntity = restTemplate.exchange(
                ARCHIVE_SEND_URL,HttpMethod.POST, requestEntry, RESPONSE_TYPE);
        if (null == responseEntity) {
            return null;
        }

        ResponseData<FileSendVO> responseData = responseEntity.getBody();
     
        return responseData;
    }

    private HttpEntity<String> buildJsonRequestEntity(Object obj) {
        if (obj == null) {
            return null;
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        try {
            HttpEntity<String> requestEntry = new HttpEntity<>(new ObjectMapper()
                .writeValueAsString(obj), headers);
            return requestEntry;
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

}

 

 

 

 

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注