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