使用restTemplate的get方法调用其他系统接口下载文件
被调用的接口
//从win10或者tomcat上下载文件
@RequestMapping(value = "/download", method = {RequestMethod.GET})
@PassToken
public String downloadFile(HttpServletRequest request, HttpServletResponse response,String id,String name) throws UnsupportedEncodingException {
String information="";
String fileName = name;
String s = tmodeluseMapper.downloadDocument(name,id );
if (fileName != null) {
//设置文件路径
File file = new File("E:\\apache-tomcat-8.5.5\\"+s);
if (file.exists()) {
// 设置强制下载不打开
response.setContentType("application/force-download");
// 设置文件名
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"),"ISO8859-1"));
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
information= "下载成功!";
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return "下载失败";
}
调用其他接口 并且下载文件
@RequestMapping(value = "/test2", method = {RequestMethod.GET})
public void setRestTemplate(HttpServletRequest httpServletRequest,HttpServletResponse response,String id,String name) throws IOException {
String url = "http://localhost:8080/tcartransfer/download?id="+id+"&name="+name;
HttpHeaders headers = new HttpHeaders();
headers.add("token",httpServletRequest.getHeader("token"));
headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML));
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<byte[]> exchange = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class);
try {
response.setHeader("Content-disposition", "attachment;filename=text" + name);
//getOutputStream引擎创建的字节输出流对象
response.getOutputStream().write(exchange.getBody());
} catch (IOException e) {
System.out.println("下载失败");
}
}
调用其他接口 保存在本机
@RequestMapping(value = "/test2", method = {RequestMethod.GET})
public void setRestTemplate(HttpServletRequest httpServletRequest) throws IOException {
String url = "http://localhost:8080/tcartransfer/download?id=00000177-3e1a-5bd6-54e9-346afd154084&name=1606893694(1).png";
HttpHeaders headers = new HttpHeaders();
headers.add("token",httpServletRequest.getHeader("token"));
headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML));
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<byte[]> exchange = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class);
System.out.println("文件下载请求结果状态码:" + exchange.getStatusCode());
// 将下载下来的文件内容保存到本地
String targetPath = "C:\\Users\\Administrator\\Desktop\\qywx\\splash-down.png";
Files.write(Paths.get(targetPath), Objects.requireNonNull(exchange.getBody(),
"未获取到下载文件"));
}