根據一個oss的pdf文件的 地址轉換成一個File文件


/**
 * 根據文件地址返回 File
 * @param url 地址
 * @return
 */
public static File doGetDownload(String url) {
    String separator=File.separator;
    String dir="ExistingEvidence/"+separator+"downLoad/";
    String fileName=System.currentTimeMillis()+".pdf";
    String path = dir+fileName;
    HttpClient httpClient = null;
    HttpGet httpPost = null;
    try {
        httpClient = new SSLClient();
        httpPost = new HttpGet(url);
        ProxyHttpClient.getProxyHttpClient(httpClient);
        HttpResponse response = httpClient.execute(httpPost);
        if (response == null) {
            throw new RuntimeException("HttpResponse is null.");
        }
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            if (null == entity) {
                throw new RuntimeException("HttpEntity is null.");
            }
            // 下載成功返回文件流
            if (!"application/zip".equals(response.getEntity().getContentType().getValue()) && !"application/pdf".equals(response.getEntity().getContentType().getValue())) {
                // 下載失敗返回json格式報文
                return null;
            }
            byte[] result = EntityUtils.toByteArray(response.getEntity());
            BufferedOutputStream bw = null;
            try {
                File f = new File(path); // 創建文件對象
                if (f.exists()) { // 重復時候替換掉
                    f.delete();
                }
                if (!f.getParentFile().exists()) { // 創建文件路徑
                    f.getParentFile().mkdirs();
                }
                bw = new BufferedOutputStream(new FileOutputStream(path));// 寫入文件
                bw.write(result);
                return f;
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    if (bw != null) {
                        bw.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            throw new RuntimeException("connect fail. http_status:" + response.getStatusLine().getStatusCode());
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        try {
            httpClient.getConnectionManager().shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM