JAVA-HTTP访问外部接口返回压缩包流,保存到本地,解压并移动文件


步骤:

一、创建HTTP请求,获取到压缩包流

二、获取zip压缩包流并保存成压缩文件到本地

三、解压

四、移动文件到指定位置

第一步  创建HTTP请求,获取到压缩包流

/**
     * 访问获取json数据(自定义表头),返回输入流
     * @param url
     * @param jsonObject
     * @return
     */
private InputStream getDoPostStream(String url, String token, String siteId, JSONObject jsonObject){
        // 创建Http Post请求
        HttpPost httpPost = new HttpPost(url);
        log.info("创建Http Post请求");
        //自定义请求头,不需要就不写 
        httpPost.setHeader("access-token",token);
        httpPost.setHeader("site-id",siteId);
        return this.doPostForStream(httpPost, jsonObject);
    }    

/**
     * POST请求,获取压缩包流
     * @param httpPost
     * @param json请求体内容为JSON格式,没有请求体内容就不需要
     * @return
     */
public static InputStream doPostForStream(HttpPost httpPost, JSONObject json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        InputStream inputStream = null;
        if (null == httpClient) {
            httpClient = HttpClientBuilder.create().build();
        }
        //api_gateway_auth_token自定义header头,用于token验证使用
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        try {
            StringEntity se = new StringEntity(json.toString());
            se.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            se.setContentType("application/json");
            //设置请求参数
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 执行http请求
                response = httpClient.execute(httpPost);
                inputStream = response.getEntity().getContent();
                return inputStream;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return inputStream;
    }

 

第二步  获取zip压缩包流并保存成压缩文件到本地

//请求头所需字段
String beforeSiteId  = "1";
String beforeToken = "token";
//请求体内容JSON()
JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(map));
//压缩包保存位置(自定义)
String zipPath = ”/html/static/sub/“ + File.separator + "content.zip";     
//请求外部接口url   
String attachmentUrl = this.beforeUrlPrefix + "/cms/content/export";
//通过请求获取到流数据
//创建将数据写入到文本文件的文件输出流
        try(InputStream inputStream  = this.getDoPostStream(attachmentUrl,this.beforeToken,this.beforeSiteId, jsonObject1);
            FileOutputStream fos = new FileOutputStream(zipPath);
            ByteArrayOutputStream byteArray = new ByteArrayOutputStream() ){
            byte[] byt = new byte[1024];
            int ch ;
            // 以字符方式显示文件内容
            while((ch = inputStream.read(byt)) > 0) {
                byteArray.write(byt,0, ch);
                byteArray.flush();
            }
            fos.write(byteArray.toByteArray());
        }catch (Exception e){
            log.error(e.getMessage());
        }    

 

第三步 解压

/**
     * zip文件解压
     * @param inputFile  待解压文件夹/文件路径
     * @param destDirPath  解压路径
     */
    public static void zipUncompress(String inputFile,String destDirPath) throws FileNotFoundException {
        //获取当前压缩文件
        File srcFile = new File(inputFile);
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new FileNotFoundException(srcFile.getPath() + "所指文件不存在");
        }
        //创建压缩文件对象
        try(ZipFile zipFile = new ZipFile(srcFile)) {
            //开始解压
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                // 如果是文件夹,就创建个文件夹
                if (entry.isDirectory()) {
                    srcFile.mkdirs();
                } else {
                    // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + File.separator + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    if (!targetFile.getParentFile().exists()) {
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    try (InputStream is = zipFile.getInputStream(entry) ;
                         FileOutputStream fos = new FileOutputStream(targetFile)){
                        int len;
                        byte[] buf = new byte[1024];
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

 

第四步 移动文件到指定位置

/**
     * 获取稿件全部数据,并移动附件
     * 数据类型:Map<String,Object>
     * @param strPath 解压后的文件路径
     * @throws Exception
     */
    public void refreshFileList(String strPath) throws Exception {
        //该map用于存放稿件数据,以及附件的路径
        Map<String,Object> dataMap = new HashMap<>();
        File dir = new File(strPath);
        File[] files = dir.listFiles();
        if (files == null){
            return ;
        }
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                refreshFileList(files[i].getAbsolutePath());
            } else {
                String strFileName = files[i].getName();
                //移动附件,返回附件的最终路径
                String fileEndPath = renameToFile(strFileName, files[i].getAbsolutePath());
            }
        }
    }

    /**
     * 移动文件,返回文件最终路径
     * @param fileName 文件名
     * @param fileStartPath 文件源路径
     * @return
     */
    public static String renameToFile(String fileName ,String fileStartPath ){
        //源文件路径
        File startFile=new File(fileStartPath);
        //文件重命名
        //fileName = "AAA" + fileName;
        //设置目的目录路径(自定义)
        String proposalFolder = "" + File.separator + "sub" + File.separator + "proposal";
        File endDirection=new File(proposalFolder);
        //如果目的目录路径不存在,则进行创建
        if(!endDirection.exists()) {
            endDirection.mkdirs();
        }
        //目的文件路径=目的目录路径+源文件名称
        File endFile = new File(proposalFolder + File.separator + fileName);
        try {
            //调用File类的核心方法renameTo
            if (startFile.renameTo(endFile)) {
                log.info("文件移动成功!目标路径:{}",endFile.getAbsolutePath());
            } else {
                log.info("文件移动失败!起始路径:{}",startFile.getAbsolutePath());
            }
        }catch(Exception e) {
            log.info("文件移动出现异常!起始路径:{}",startFile.getAbsolutePath());
        }
        //返回文件的访问路径(自定义)
        return "" + "proposal/" + fileName;
    }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM