JRT整合下载文件api

发布时间:2023年12月21日

以前最古老的是用的FTP存文件,所以原始的文件操作是直接操作FTP,后面随着使用发现FTP对端口要求太多了,容易出问题,新的安保方面也提安全方面问题,就转http文件服务了。为了同时兼容两种文件服务,此时就抽取文件服务操作API,把上传、下载、移动等API整合成一套给业务用,业务不需要关心文件服务是FTP还是HTTP。

有了文件服务API抽取之后就能干很多有意思的事了,因为业务可以无视FTP和HTTP差异操作,所以从url拉取外部文件进内部文件服务就很简单。就可以各种FTP、HTTP互操作。因为我们自己已经不用FTP当文件服务了,所以不需要实现FTP上传那些API了,但是不能管住别人不给你FTP的URL,所以下载还是要兼容FTP的,这次给下载API支持FTP下载。

实现代码:

    /**
     * 从服务下载文件
     *
     * @param fileServerFullPath 文件在服务的全路径
     * @param fileFullName       文件本地保存的全路径
     * @param passive
     * @return 成功返回空串,否则返回失败原因
     */
    public String Download(String fileServerFullPath, String fileFullName, boolean passive) {
        try {
            //普通ftp模式,ftp://zlz:zlz@127.0.0.1:21/ftp.png
            if (fileServerFullPath.toLowerCase().contains("ftp://")) {
                InputStream responseStream = null;
                FileOutputStream fileOutputStream = null;
                try {
                    URL url = new URL(fileServerFullPath);
                    //打开连接
                    URLConnection connection = url.openConnection();
                    //提取用户密码
                    String[] pathArr = fileServerFullPath.split("/");
                    String userPass = pathArr[2];
                    //设置用户和密码
                    if (userPass.contains("@")) {
                        String[] userPassArr = userPass.split("@");
                        String[] passArr = userPassArr[0].split(":");
                        //设置用户密码
                        connection.setRequestProperty("USER", passArr[0]);
                        connection.setRequestProperty("PASS", passArr[1]);
                    }
                    //设置FTP模式
                    if (passive == true) {
                        connection.setRequestProperty("PASV", "true");
                    }
                    responseStream = connection.getInputStream();
                    Path fileFullNameP = Paths.get(fileFullName);
                    Path directoryName = fileFullNameP.getParent();
                    //本地路径不存在就创建
                    if (!Files.exists(directoryName)) {
                        Files.createDirectories(directoryName);
                    }
                    //文件存在就删除
                    if (Files.exists(fileFullNameP)) {
                        Files.delete(fileFullNameP);
                    }
                    fileOutputStream = new FileOutputStream(fileFullName);
                    // 创建一个byte数组来缓存读取的数据
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    // 读取InputStream中的数据,并将其写入到文件中
                    while ((bytesRead = responseStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, bytesRead);
                    }
                    return "";
                } catch (Exception ee) {
                    return ee.getMessage();
                } finally {
                    if (responseStream != null) {
                        responseStream.close();
                    }
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                }
            }
            //检验http模式
            else if (fileServerFullPath.toLowerCase().contains("http://") || fileServerFullPath.toLowerCase().contains("https://")) {
                //忽略证书
                if (fileServerFullPath.contains("https://")) {
                    TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }

                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }

                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }
                    };
                    // Install the all-trusting trust manager
                    SSLContext sc = SSLContext.getInstance("SSL");
                    sc.init(null, trustAllCerts, new java.security.SecureRandom());
                    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                    // Create all-trusting host name verifier
                    HostnameVerifier allHostsValid = new HostnameVerifier() {
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    };
                }
                InputStream responseStream = null;
                FileOutputStream fileOutputStream = null;
                try {
                    URL u = new URL(UrlEnCode(fileServerFullPath));
                    HttpURLConnection http = (HttpURLConnection) u.openConnection();
                    http.setDoOutput(Boolean.TRUE);
                    http.setRequestMethod("GET");
                    int responseCode = http.getResponseCode();
                    responseStream = http.getInputStream();
                    Path fileFullNameP = Paths.get(fileFullName);
                    Path directoryName = fileFullNameP.getParent();
                    //本地路径不存在就创建
                    if (!Files.exists(directoryName)) {
                        Files.createDirectories(directoryName);
                    }
                    //文件存在就删除
                    if (Files.exists(fileFullNameP)) {
                        Files.delete(fileFullNameP);
                    }
                    fileOutputStream = new FileOutputStream(fileFullName);
                    // 创建一个byte数组来缓存读取的数据
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    // 读取InputStream中的数据,并将其写入到文件中
                    while ((bytesRead = responseStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, bytesRead);
                    }

                    return "";
                } catch (Exception ee) {
                    return ee.getMessage();
                } finally {
                    if (responseStream != null) {
                        responseStream.close();
                    }
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                }
            }
        } catch (Exception ex) {
            return ex.getMessage();
        }
        return "";
    }

    /**
     * 从服务下载文件
     *
     * @param fileServerFullPath 文件在服务的全路径
     * @param passive
     * @return
     */
    public InputStream DownloadStream(String fileServerFullPath, boolean passive) throws Exception {
        try {
            //普通ftp模式
            if (fileServerFullPath.toLowerCase().contains("ftp://")) {
                URL url = new URL(fileServerFullPath);
                //打开连接
                URLConnection connection = url.openConnection();
                String[] pathArr = fileServerFullPath.split("/");
                String userPass = pathArr[2];
                //设置用户和密码
                if (userPass.contains("@")) {
                    String[] userPassArr = userPass.split("@");
                    String[] passArr = userPassArr[0].split(":");
                    connection.setRequestProperty("USER", passArr[0]);
                    connection.setRequestProperty("PASS", passArr[1]);
                }
                //设置FTP模式
                if (passive == true) {
                    connection.setRequestProperty("PASV", "true");
                }
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
            //检验http模式
            else if (fileServerFullPath.toLowerCase().contains("http://") || fileServerFullPath.toLowerCase().contains("https://")) {
                //忽略证书
                if (fileServerFullPath.contains("https://")) {
                    TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }

                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }

                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }
                    };
                    // Install the all-trusting trust manager
                    SSLContext sc = SSLContext.getInstance("SSL");
                    sc.init(null, trustAllCerts, new java.security.SecureRandom());
                    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                    // Create all-trusting host name verifier
                    HostnameVerifier allHostsValid = new HostnameVerifier() {
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    };
                }
                URL u = new URL(UrlEnCode(fileServerFullPath));
                HttpURLConnection http = (HttpURLConnection) u.openConnection();
                http.setDoOutput(Boolean.TRUE);
                http.setRequestMethod("GET");
                int responseCode = http.getResponseCode();
                InputStream responseStream = http.getInputStream();
                return responseStream;
            }
        } catch (Exception ex) {
            throw ex;
        }
        return null;
    }

取图用文件服务取
在这里插入图片描述

打印测试

在这里插入图片描述

在这里插入图片描述

这样,文件服务的API就算集齐了

文章来源:https://blog.csdn.net/zhanglianzhu_91/article/details/135136591
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。