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;
    }

版权声明:本文为qq_30581017原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。