OkHttpClient读取/下载网络资源文件

 <!--okhttp-->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.3.1</version>
        </dependency>
    <bean class="okhttp3.OkHttpClient"/>



    /**
     * 下载文件到本地
     *
     * @param sourceUrl
     * @param dir
     * @param prefix
     * @param fileName
     * @return
     */
    public String downloadFileByUrl(String sourceUrl, String dir, String prefix, String fileName) {
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String localPath = dir + File.separator + prefix + "-" + fileName + ".zip";
        File file = new File(localPath);

        Request request = new Request.Builder()
                .url(sourceUrl)
                .build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            if (response.code() == 200) {
                InputStream stream = response.body().byteStream();
                Files.copy(stream, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } else {
                logger.error(response.code() + ":" + response.message());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return localPath;
    }
public String processor(String sourceUrl, String sourceHash, String uuid) {
        String accessUrl = "";

        //下载文件
        String localFileDest = downloadFileByUrl(sourceUrl, localPath, prefix, uuid);

        //下载文件是否存在
        File file = new File(localFileDest);
        if (!file.exists()) {
            logger.error("local file of downloading not exist,localPath:{}", localFileDest);
            return accessUrl;
        }

        //下砸文件是否完整
        String localHash = FileUtil.md5(file);
        if (StringUtils.isEmpty(localHash) || !StringUtils.equals(localHash, sourceHash)) {
            logger.error("local fileHash:{} is not same as receiveFileHash:{}", localHash, sourceHash);
            //删除下载文件
            file.delete();
            return accessUrl;
        }

        //下载成功,上传到私有资源库
        String ret = uploadFileToXXX(localFileDest, prefix, uuid);
        file.delete();
        if (!StringUtils.isEmpty(ret)) {
            try {
                //解析上传结果
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        return accessUrl;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值