Spring RestTemplate相关使用积累
RestTemplate中请求数据
需求涉及到Rest API调用,需要进行传参,基于传参获得JSON,JSON比较大,需要将数据以JSON保存在在本地磁盘,再通过Fastjson的StreamAPI分批读入,在获取相关数据,存储到DB中,在JSON保存,也尽量保障不占用大内存,所以使用JAVA NIO中的Files.copy。
1. 使用exchange方式直接调用,并且以流返回,存储json文件
这里在Accept上以(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL) application/octet-stream, / 作为header中的Accept,以byte[]返回回来,全部读入到内存,文件过大,比如会导致内存占用过高
public void exchangeByteMethod() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
headers.set("APP-ID","xxxx");
headers.set("APP-TOKEN","xxxxx");
Person person = new Person("dufangming", 25, 170);
HttpEntity<Person> httpEntity = new HttpEntity<>(person, headers);
ResponseEntity<byte[]> responseEntity = null;
File file = new File("xxxxx\\data\\3.json");
try {
responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, byte[].class);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(responseEntity.getBody());
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
log.error("exchange调用方法出错", e);
}
}
所以使用部分数据逐步读入到文件中,是最好的
2. 使用execute方法进行调用
execute()中的RequestCallback、ResponseExtractor,这样更加底层的使用resttemplate的的方法,但是重新@Override太复杂(主要是搞不定)
使用一个扩展RestTemplate的方法,将底层public httpEntityCallbak方法就可以调用了,这样就可以实现传参到Server端,调用execute2的方法处理
public class DownLoadRestTemplate extends RestTemplate {
public <T> T execute2(String uriTemplate, HttpMethod method, HttpEntity httpEntity, ResponseExtractor<T> responseExtractor) throws RestClientException {
return super.execute(uriTemplate, method, this.httpEntityCallback(httpEntity), responseExtractor);
}
}
通过传参获取JSON并且进行保存
/**
* 实现传递参数,并且以流获取服务端数据,保存为json文件
*/
public void excuteMethod() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
headers.set("APP-ID","xxxxx");
headers.set("APP-TOKEN","xxxx");
Person person = new Person("dufangming", 25, 170);
HttpEntity<Person> httpEntity = new HttpEntity<>(person, headers);
String fileNamePath = "xxxx\\data\\10.json";
restTemplate.execute2(url, HttpMethod.POST, httpEntity, clientHttpResponse -> {
Files.copy(clientHttpResponse.getBody(), Paths.get(fileNamePath));
return null;
});
}
参考:精讲RestTemplate第6篇-文件上传下载与大文件流式下载_字母哥哥的博客-CSDN博客_resttemplate 下载)