如何使用代理連接FTPS
最近公司需要有一個需求,要將文檔傳輸到外部供應商FTP中,並且連接外網都是由公司中央網通管控的,我們需要訪問外部供應商必須要用代理連接供應商。
不說那麼多了,上代碼,減少以後朋友們開發的時間。
public class ProxyFtpUtils implements Ftp {private static final Logger log = LoggerFactory.getLogger(ProxyFtpUtils.class);/*** ftp服務器地址*/private String hostname;/*** ftp服務器端口號默認爲21*/private Integer port;/*** ftp登錄賬號*/private String username;/*** ftp登錄密碼*/private String password;private String proxyHost;private Integer proxyPort;public ProxyFtpUtils(String hostname, Integer port, String username, String password, String proxyHost, Integer proxyPort) {super();this.hostname = hostname;this.port = port;this.username = username;this.password = password;this.proxyHost = proxyHost;this.proxyPort = proxyPort;}public FTPSHTTPClient ftps;/*** 初始化ftp服務器*/private void initFtpClient() {ftps = new FTPSHTTPClient (proxyHost, proxyPort);ftps.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));ftps.setRemoteVerificationEnabled(false);ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());ftps.setDataTimeout(1800000);try {//设置字符集编码,避免乱码问题ftps.setControlEncoding(CharsetUtil.UTF_8);ftps.connect(hostname, port);log.info("ftp connect**** :"+hostname+"/"+port);//登录ftp服务器ftps.login(username, password);log.info("ftp login**** :"+username+"/"+password);((FTPSClient) ftps).execPROT("P");log.info("ftp setFileType**** :"+FTP.BINARY_FILE_TYPE);//这个设置允许被动连接--访问远程ftp时需ftps.enterLocalPassiveMode();log.info("ftp set PassiveMode***************** ");ftps.setFileType(FTP.BINARY_FILE_TYPE);//proxyClient.enterLocalPassiveMode();ftps.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);//是否成功登录服务器int replyCode = ftps.getReplyCode();log.info("是否登录成功--------> " + replyCode);//return(reply >= 200 && reply < 300)不是这个范围的就是失败if (!FTPReply.isPositiveCompletion(replyCode)) {//失败log.error("未连接到FTP服务器,用户名或密码错误");//连接失败,更新FTP服务状态hostname = null;} else {//成功log.info("FTP服务器连接成功"+hostname+"/"+port+"/"+username+"/"+password);}} catch (MalformedURLException e) {log.error("connect ftp server fail...", e);} catch (IOException e) {log.error("connect ftp server fail...", e);}}public FTPClient getFtpClient(){initFtpClient();return this.ftps;}
@Override
public boolean uploadFileNew(String pathname, String fileName, InputStream inputStream) {boolean flag = false;try {initFtpClient();//ftpClient.setFileType(FTP.BINARY_FILE_TYPE);createDirecroty(pathname);ftps.storeFile(fileName, inputStream);inputStream.close();ftps.logout();flag = true;} catch (Exception e) {e.printStackTrace();} finally {if (ftps.isConnected()) {try {ftps.disconnect();} catch (IOException e) {e.printStackTrace();}}if (null != inputStream) {try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}}return flag;
}
public void close() {if (ftps != null && ftps.isConnected()) {try {ftps.disconnect();} catch (IOException e) {log.error("disconnect ftp error", e);}}}public void close(InputStream inputStream) {if (ftps != null && ftps.isConnected()) {try {ftps.disconnect();} catch (IOException e) {log.error("disconnect ftp error", e);}}if (inputStream != null) {try {inputStream.close();} catch (IOException e) {log.error("close input stream error", e);}}}public void close(OutputStream outputStream) {if (ftps != null && ftps.isConnected()) {try {ftps.disconnect();} catch (IOException e) {log.error("disconnect ftp error", e);}}if (outputStream != null) {try {outputStream.close();} catch (IOException e) {log.error("close output stream error", e);}}}//改變目錄路徑private boolean changeRemoteWorkingDirectory(String directory) {boolean flag = true;try {flag = ftps.changeWorkingDirectory(directory);} catch (IOException ioe) {ioe.printStackTrace();}return flag;}/*** 創建多層目錄文件,如果有ftp服務器已存在該文件,則不創建,如果無,則創建** @param remote* @return* @throws IOException*/private boolean createDirecroty(String remote) throws IOException {boolean success = true;String directory = new File(remote).getPath() + File.separator;// 如果遠程目錄不存在,則遞歸創建遠程服務器目錄if (!directory.equalsIgnoreCase(File.separator) && !changeRemoteWorkingDirectory(directory)) {int start = 0;int end = 0;if (directory.startsWith(File.separator)) {start = 1;} else {start = 0;}end = directory.indexOf(File.separator, start);String path = "";String paths = "";while (true) {String subDirectory = remote.substring(start, end);path = path + File.separator + subDirectory;if (!existFile(subDirectory)) {if (makeDirectory(subDirectory)) {changeRemoteWorkingDirectory(subDirectory);} else {changeRemoteWorkingDirectory(subDirectory);}} else {changeRemoteWorkingDirectory(subDirectory);}paths = paths + File.separator + subDirectory;start = end + 1;end = directory.indexOf(File.separator, start);// 檢查所有目錄是否創建完畢if (end <= start) {break;}}}return success;}/*** 判斷ftp服務器文件是否存在*/@Overridepublic boolean existFile(String path) {boolean init = false;if (ftps == null) {initFtpClient();init = true;}boolean flag = false;try {FTPFile[] ftpFileArr = ftps.listFiles(path);if (ftpFileArr.length > 0) {flag = true;}if (init) {ftps.logout();if (ftps.isConnected()) {ftps.disconnect();}}} catch (Exception e) {e.printStackTrace();}return flag;}/*** 創建目錄** @author H2103610* @description* @date 2021-03-04 11:14* @version 1.0**/private boolean makeDirectory(String dir) {boolean flag = false;try {flag = ftps.makeDirectory(dir);} catch (Exception e) {e.printStackTrace();}return flag;}/*** 下載文件 *** @param filePath FTP服務器文件目錄 ** @param localPath 下載後的文件路徑 ** @return*/@Overridepublic String downloadFile(String filePath, String localPath) {String fileFullPath = null;OutputStream os = null;File dir = new File(localPath);if (!dir.exists()) {dir.mkdirs();}try {initFtpClient();//切換FTP目錄FTPFile[] ftpFiles = ftps.listFiles(filePath);for (FTPFile file : ftpFiles) {File localFile = new File(dir, file.getName());fileFullPath = localFile.getAbsolutePath();os = new FileOutputStream(localFile);ftps.retrieveFile(filePath, os);os.flush();break;}ftps.logout();} catch (Exception e) {log.error("connect ftp server error...", e);} finally {if (ftps.isConnected()) {try {ftps.disconnect();} catch (IOException e) {log.error("connect ftp server error...", e);}}if (null != os) {try {os.close();} catch (IOException e) {log.error("close stream error...", e);}}}return fileFullPath;}public File getFile(String filePath, String localPath) {File dir = new File(localPath);File localFile = null;if (!dir.exists()) {dir.mkdirs();}try {initFtpClient();//切換FTP目錄FTPFile[] ftpFiles = ftps.listFiles(filePath);for (FTPFile file : ftpFiles) {localFile = new File(dir, file.getName());break;}ftps.logout();} catch (Exception e) {log.error("connect ftp server error...", e);} finally {if (ftps.isConnected()) {try {ftps.disconnect();} catch (IOException e) {log.error("connect ftp server error...", e);}}}return localFile;}/*** 下載文件 *** @param filePath FTP服務器文件目錄 ** @param os* @return*/@Overridepublic int downloadFile(String filePath, OutputStream os) {int fileSize = 0;try {initFtpClient();//切換FTP目錄FTPFile[] ftpFiles = ftps.listFiles(filePath);for (FTPFile file : ftpFiles) {fileSize = (int) file.getSize();ftps.retrieveFile(filePath, os);os.flush();break;}ftps.logout();} catch (Exception e) {log.error("connect ftp server error...", e);} finally {if (ftps.isConnected()) {try {ftps.disconnect();} catch (IOException e) {log.error("disconnect ftp server error...", e);}}if (null != os) {try {os.close();} catch (IOException e) {log.error("close stream error...", e);}}}return fileSize;}/*** 刪除文件 *** @param filePath FTP服務器保存目錄* @return*/@Overridepublic boolean deleteFile(String filePath) {boolean flag = false;boolean init = false;try {if (ftps == null) {initFtpClient();init = true;}ftps.deleteFile(filePath);} catch (Exception e) {log.error("delete ftp file error...", e);} finally {if (init) {try {ftps.logout();if (ftps.isConnected()) {ftps.disconnect();}} catch (IOException e) {log.error("disconnect ftp server error...", e);}}}return flag;}/*** 刪除文件 *** @param dir FTP服務器保存目錄* @return*/@Overridepublic boolean deleteDirectory(String dir) {dir = dir.replaceAll("\\\\", "/");if (dir.endsWith("/")) {dir = dir.substring(0, dir.length() - 1);}boolean flag = false;boolean init = false;try {if (ftps == null) {initFtpClient();init = true;}ftps.removeDirectory(dir);FTPFile[] files = ftps.listFiles(dir);for (FTPFile file : files) {String filePath = dir + "/" + file.getName();if (file.isDirectory()) {deleteDirectory(filePath);} else {ftps.deleteFile(filePath);}}flag = ftps.removeDirectory(dir);} catch (Exception e) {log.error("delete ftp directory error...", e);} finally {if (init) {try {ftps.logout();if (ftps.isConnected()) {ftps.disconnect();}} catch (IOException e) {log.error("disconnect ftp server error...", e);}}}return flag;}@Overridepublic long calcCapacity(String path) {long size = 0;initFtpClient();try {size = getCapacity(path);} catch (Exception e) {e.printStackTrace();} finally {try {ftps.logout();ftps.disconnect();} catch (Exception e) {log.error("disconnect ftp server error...", e);}}return size;}private long getCapacity(String path) {try {long size = 0;FTPFile[] files = ftps.listFiles(path);for (FTPFile file : files) {if (file.isDirectory()) {size += getCapacity(path + "/" + file.getName());} else {size += file.getSize();}}return size;} catch (Exception e) {log.error("connect ftp server error...", e);}return 0;}@Overridepublic void downloadFileResp(String filePath, HttpServletResponse resp) throws IOException {downloadFile(filePath, resp.getOutputStream());}/*** 下載文件*** @param filePath FTP服務器文件目錄 ** @return*/public List downloadFile2B64(String filePath) {List fileNames = new ArrayList<>();ByteArrayOutputStream bos = null;ByteArrayInputStream fis = null;InputStream retrieveFileStream = null;try {initFtpClient();//切換FTP目錄FTPFile[] ftpFiles = ftps.listFiles(filePath);for (FTPFile file : ftpFiles) {long start = System.currentTimeMillis();retrieveFileStream = ftps.retrieveFileStream(filePath);if (null == retrieveFileStream) {throw new FileNotFoundException(filePath);}bos = new ByteArrayOutputStream();int length;byte[] buf = new byte[2048];while (-1 != (length = retrieveFileStream.read(buf, 0, buf.length))) {bos.write(buf, 0, length);}fis = new ByteArrayInputStream(bos.toByteArray());bos.flush();byte[] buffer = new byte[fis.available()];int offset = 0;int numRead = 0;while (offset < buffer.length && (numRead = fis.read(buffer, offset, buffer.length - offset)) >= 0) {offset += numRead;}if (offset != buffer.length) {throw new IOException("Could not completely read file ");}String asB64 = "data:image/jpg;base64,"+new Base64Encoder().encode(buffer);fileNames.add(asB64);long end = System.currentTimeMillis();System.out.println(end-start);}ftps.logout();} catch (Exception e) {log.error("connect ftp server error...", e);} finally {if (ftps.isConnected()) {try {ftps.disconnect();} catch (IOException e) {log.error("disconnect ftp server error...", e);}}if (null != bos) {try {bos.close();} catch (IOException e) {log.error("close stream error...", e);}}if (null != fis) {try {fis.close();} catch (IOException e) {log.error("close stream error...", e);}}if (null != retrieveFileStream) {try {retrieveFileStream.close();} catch (IOException e) {log.error("close stream error...", e);}}}return fileNames;}public boolean createDir(String destDirName) {File dir = new File(destDirName);if (dir.exists()) {log.info("创建目录" + destDirName + "失败,目标目录已经存在");return false;}if (!destDirName.endsWith(File.separator)) {destDirName = destDirName + File.separator;}//创建目录if (dir.mkdirs()) {log.info("创建目录" + destDirName + "成功!");return true;} else {log.info("创建目录" + destDirName + "失败!");return false;}}/*** 下載文件 ** @param remoteClient fdm ftpclient* @param fdmUrl FDM FTP服務器文件目錄 ** @param localPath oem FTP下載後的文件路徑 ** @return*/public Boolean copyFileToFtp(FTPClient remoteClient,FTPClient localClient, String fdmUrl,String baseDir, String localPath) throws CopyFileException {OutputStream outputStream = null;Boolean b = false;try {remoteClient.enterLocalPassiveMode();remoteClient.setControlEncoding("UTF-8");FTPFile[] ftpFiles = remoteClient.listFiles(fdmUrl);for (FTPFile file : ftpFiles) {long size = file.getSize();InputStream retrieveFileStream = remoteClient.retrieveFileStream(fdmUrl);if (null == retrieveFileStream) {throw new FileNotFoundException(fdmUrl);}if(localPath != null && !"".equals(localPath)){this.createDir(baseDir + localPath);}File fileLocal = new File(baseDir + localPath +"/"+ file.getName());OutputStream localFile = new FileOutputStream(fileLocal);byte[] buf = new byte[1024];int length;while((length = retrieveFileStream.read(buf))>0){localFile.write(buf,0,length);}localFile.flush();if(localFile != null){localFile.close();}File fileLocal2 = new File(baseDir + localPath +"/"+ file.getName());InputStream localFile2 = new FileInputStream(fileLocal2);createRemoteDirecroty(localClient,localPath);b = localClient.storeFile(file.getName(),localFile2);if(b){log.info("上传成功");}else{log.info("上传失败");}if(localFile2 != null){localFile2.close();}/*boolean x = localClient.completePendingCommand();if(x){log.info("上传成功");}else{log.info("上传失败");}*/}} catch (IOException e) {e.printStackTrace();throw new CopyFileException(e);}finally {if (localClient.isConnected()) {try {localClient.disconnect();} catch (IOException e) {log.error("connect ftp server error...", e);}}if (remoteClient.isConnected()) {try {remoteClient.disconnect();} catch (IOException e) {log.error("connect ftp server error...", e);}}if (null != outputStream) {try {outputStream.close();} catch (IOException e) {log.error("close stream error...", e);}}}return b;}/*** 發送文件到供應商ftp **/public Boolean sendFileToFtp(FTPClient remoteClient,FTPClient localClient, String localBaseDir, String localPath ,String remotePath) throws CopyFileException {OutputStream outputStream = null;InputStream inputStream = null;Boolean b = false;try {localClient.enterLocalPassiveMode();localClient.setControlEncoding("UTF-8");FTPFile[] ftpFiles = localClient.listFiles(localPath);for (FTPFile file : ftpFiles) {long size = file.getSize();InputStream retrieveFileStream = localClient.retrieveFileStream(localPath);if (null == retrieveFileStream) {throw new FileNotFoundException(localPath);}if(localPath != null && !"".equals(localPath)){this.createDir(localPath);}File fileLocal = new File(localBaseDir + localPath +"/"+ file.getName());outputStream = new FileOutputStream(fileLocal);byte[] buf = new byte[1024];int length;while((length = retrieveFileStream.read(buf))>0){outputStream.write(buf,0,length);}outputStream.flush();File fileLocal2 = new File(localBaseDir + localPath +"/"+ file.getName());inputStream = new FileInputStream(fileLocal2);localClient.enterLocalPassiveMode();createRemoteDirecroty(remoteClient,remotePath);b = remoteClient.storeFile(file.getName(),inputStream);if(b){log.info("上传成功");}else{log.info("上传失败");}}} catch (IOException e) {e.printStackTrace();throw new CopyFileException(e);}finally {if (localClient.isConnected()) {try {localClient.disconnect();} catch (IOException e) {log.error("connect ftp server error...", e);}}if (remoteClient.isConnected()) {try {remoteClient.disconnect();} catch (IOException e) {log.error("connect ftp server error...", e);}}if (null != outputStream) {try {outputStream.close();} catch (IOException e) {log.error("close stream error...", e);}}if (null != inputStream) {try {inputStream.close();} catch (IOException e) {log.error("close stream error...", e);}}}return b;}/*** 創建多層目錄文件,如果有ftp服務器已存在該文件,則不創建,如果無,則創建**/private boolean createRemoteDirecroty(FTPClient remoteClient,String remote) throws IOException {boolean success = true;String directory = new File(remote).getPath() + File.separator;// 如果遠程目錄不存在,則遞歸創建遠程服務器目錄if (!directory.equalsIgnoreCase(File.separator) && !changeWorkingRemoteDirectory(remoteClient,directory)) {int start = 0;int end = 0;if (directory.startsWith(File.separator)) {start = 1;} else {start = 0;}end = directory.indexOf(File.separator, start);String path = "";String paths = "";while (true) {String subDirectory = remote.substring(start, end);path = path + File.separator + subDirectory;if (!existRemoteFile(remoteClient,subDirectory)) {if (makeRemoteDirectory(remoteClient,subDirectory)) {changeWorkingRemoteDirectory(remoteClient,subDirectory);} else {changeWorkingRemoteDirectory(remoteClient,subDirectory);}} else {changeWorkingRemoteDirectory(remoteClient,subDirectory);}paths = paths + File.separator + subDirectory;start = end + 1;end = directory.indexOf(File.separator, start);// 檢查所有目錄是否創建完畢if (end <= start) {break;}}}return success;}//改變目錄路徑private boolean changeWorkingRemoteDirectory(FTPClient remoteClient,String directory) {boolean flag = true;try {flag = remoteClient.changeWorkingDirectory(directory);} catch (IOException ioe) {ioe.printStackTrace();}return flag;}/*** 判斷ftp服務器文件是否存在*/public boolean existRemoteFile(FTPClient remoteClient,String path) {boolean init = false;if (remoteClient == null) {initFtpClient();init = true;}boolean flag = false;try {FTPFile[] ftpFileArr = remoteClient.listFiles(path);if (ftpFileArr.length > 0) {flag = true;}if (init) {remoteClient.logout();if (remoteClient.isConnected()) {remoteClient.disconnect();}}} catch (Exception e) {e.printStackTrace();}return flag;}/*** 創建目錄***/private boolean makeRemoteDirectory(FTPClient remoteClient,String dir) {boolean flag = false;try {flag = remoteClient.makeDirectory(dir);} catch (Exception e) {e.printStackTrace();}return flag;}public Boolean copyFileToLocalFtp(FTPClient localClient, String url,String outEncryptPath) throws CopyFileException{Boolean isok = false;InputStream localStream = null;try {File localFile = new File(url);localStream = new FileInputStream(localFile);if(localStream != null){//localClient.setControlEncoding("UTF-8");//localClient.enterLocalPassiveMode();//localClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);createRemoteDirecroty(localClient,outEncryptPath);isok = localClient.storeFile(localFile.getName(), localStream);//isok = localClient.completePendingCommand();if(isok){log.info("上传成功");}else{log.info("上传失败");}}} catch (IOException e) {e.printStackTrace();throw new CopyFileException(e);}finally {if (localClient.isConnected()) {try {localClient.disconnect();} catch (IOException e) {log.error("connect ftp server error...", e);}}if (null != localStream) {try {localStream.close();} catch (IOException e) {log.error("close stream error...", e);}}}return isok;}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
