根据一个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();
        }
    }
}

 

posted @ 2019-07-18 14:58  An-Optimistic-Person  阅读(2022)  评论(0编辑  收藏  举报