使用RestTemplate请求远程接口下载文件

使用 RestTemplate 上传文件代码: https://blog.csdn.net/weixin_44953227/article/details/124636293

下载代码

package com.pro.web;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.pro.common.exception.BusinessException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.UUID;

@RestController
@RequestMapping("/download")
public class DownloadController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RestTemplate restTemplate;


    /**
     * 文件下载
     *
     * @param documentPath
     * @param response
     * @throws BusinessException
     */
    @GetMapping("/file")
    public void downloadFile(String documentPath, HttpServletResponse response) throws BusinessException {
        if (StringUtils.isBlank(documentPath)) {
            throw BusinessException.withErrorMsg("文档地址为空");
        }

        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity<String> httpEntity = new HttpEntity<>(httpHeaders);

        String url = String.format("https://img-home.csdnimg.cn/images/20201124032511.png");
        logger.info(">>> 下载文件url: {}", url);
        URI uri = null;
        try {
            uri = new URI(url);
        } catch (URISyntaxException e) {
            logger.error("uri 异常", e);
            throw BusinessException.withErrorMsg(e);
        }

        ResponseEntity<byte[]> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, byte[].class);
        logger.warn(">>> responseEntity: {}", responseEntity);

        if (responseEntity.getStatusCodeValue() != HttpStatus.OK.value()) {
            logger.error(">>> 状态码异常: {}", responseEntity.getStatusCodeValue());
            throw BusinessException.withErrorMsg(String.format("状态码异常 %s", responseEntity.getStatusCodeValue()));
        }

        // 把 body 数据写入输出流
        byte[] data = responseEntity.getBody();
        if (data == null) {
            throw BusinessException.withErrorMsg("文件为空");
        }

        ServletOutputStream outputStream = null;
        try {
            String uid = UUID.randomUUID().toString().replace("-", "");
            String fileName = String.format("%s_%s.png", uid, documentPath);

            // 设置这两个参数后浏览器会自动下载, 这两个参数可以不设置, 不设置在会在浏览器中显示文件内容
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

            outputStream = response.getOutputStream();
            // 输出
            outputStream.write(data);
            outputStream.flush();
        } catch (IOException e) {
            logger.error("IOException", e);
        } finally {
            // 关闭流
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    logger.error("close IOException", e);
                }
            }
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值