JAVA 记录内网服务通过外网服务获取文件流

        公司项目遇到,对接第三方接口时需要根据链接获取网络文件保存到我们自己的服务器,但是本服务无法访问外网,只能通过请求另一个服务去访问外网。故准备由外网服务获取网络文件并将文件流推送回内网服务进行保存。

外网服务接口:

@RestController
@RequestMapping("/url")
@ApiType(name = "内部接口转发")
public class UrlController extends GenericDataForFileController<HttpRequest, GeneralResponseDto> {
    @Autowired
    private HttpServletResponse response;

    @Override
    public void execute(HttpRequest req, GeneralResponseDto respData) {
        try {
            URL url = new URL(req.getUrl());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(10 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + req.getParam().toString());
            InputStream is = conn.getInputStream();
            try {
                byte[] b = new byte[1024];
                int length;
                while ((length = is.read(b)) > 0) {
                    response.getOutputStream().write(b, 0, length);
                }
            } catch (IOException e) {
                throw e;
            } finally {
                if (response.getOutputStream() != null) {
                    try {
                        response.getOutputStream().close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        } catch (MalformedURLException e) {
            logger.info("文件下载失败");
        } catch (IOException e) {
            logger.info("文件下载失败");
        }

    }
}

内网服务接口,本处文件保存用了hutool的FileUtil,属于本地保存:

/**
     * 从网络Url中下载文件
     *
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    private void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
        URL url = new URL(getStream);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置body内的参数,put到JSONObject中
        JSONObject param = new JSONObject();
        param.put("url", urlStr);
        param.put("param", fileName.substring(fileName.lastIndexOf("/") + 1));
        conn.setRequestProperty("Content-Type", "application/json");

        //设置超时间为3秒
        conn.setConnectTimeout(10 * 1000);
        //请求post方式
        conn.setRequestMethod("POST");
        // Post请求不能使用缓存
        conn.setUseCaches(false);
        // 设置是否从HttpURLConnection输入,默认值为 true
        conn.setDoInput(true);
        // 设置是否使用HttpURLConnection进行输出,默认值为 false
        conn.setDoOutput(true);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
        writer.write(param.toString());
        writer.close();
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        if (inputStream.available() < 1000) {
            throw new IOException("文件获取失败");
        }
        String upload = savePath + "/" + fileName;
        //写入
        FileUtil.writeFromStream(inputStream, upload);
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值