- 服务端调用第三方API下载文件
- 文件下载到后将文件返回到用户浏览器供用户下载
- HTTP客户端框架:Forest
- 创建API访问接口:TestApi(这里不再详细赘述,具体步骤请查阅Forest中文文档)
public interface TestApi{
@Get(url = "${baseUrl}/document/download")
@DownloadFile(dir = "", filename = "测试文件")
ForestResponse download(@Query("documentId") String documentId);
}
- 在Controller注入TestApi并下载文件
@RestController
@RequestMapping("/test")
public class TestController{
@Autowired
private TestApi testApi;
@GetMapping("download")
public void download(String documentId, HttpServletResponse response) throws Exception{
ForestResponse foResponse = testApi.download(documentId);
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", foResponse.getHeaderValue("Content-Disposition"));
byte[] buffer = new byte[1024];
try (InputStream fis = foResponse.getInputStream();
BufferedInputStream 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);
}
}
}
}