Spring Boot 调用第三方API下载文件

  • 需求描述

  1. 服务端调用第三方API下载文件
  2. 文件下载到后将文件返回到用户浏览器供用户下载
  • 工具
  1. HTTP客户端框架:Forest
  • 步骤

  1. 创建API访问接口:TestApi(这里不再详细赘述,具体步骤请查阅Forest中文文档
public interface TestApi{
	@Get(url = "${baseUrl}/document/download")
    @DownloadFile(dir = "", filename = "测试文件")
	ForestResponse download(@Query("documentId") String documentId);
}
  1. 在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);
            }
        }
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值