FTCPSClient 连接 SVFTPD服务器,服务器开启SSL认证
很多文章都介绍了FTPClient如何连接ftp服务器,但却很少有人说如何连接一台开了SSL认证的ftp服务器,现在代码来了。
##依赖
<!-- ftp远程工具 -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
<!-- pool 对象池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
代码
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPSClient;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStore;
public class FTPSExample {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String username = "your-username";
String password = "your-password";
FTPSClient ftpsClient = new FTPSClient("TLS");
try {
// 设置SSL连接相关配置
SSLContext sslContext = SSLContext.getInstance("TLS");
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream keyStoreFile = new FileInputStream("path-to-key-store-file");
keyStore.load(keyStoreFile, "key-store-password".toCharArray());
keyStoreFile.close();
keyManagerFactory.init(keyStore, "key-store-password".toCharArray());
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagers, null);
ftpsClient.setContext(sslContext);
// 连接到FTP服务器
ftpsClient.connect(server, port);
ftpsClient.login(username, password);
// 设置文件传输模式为二进制
ftpsClient.setFileType(FTP.BINARY_FILE_TYPE);
// 上传文件
File localFile = new File("local-file.txt");
String remoteFile = "remote-file.txt";
FileInputStream inputStream = new FileInputStream(localFile);
ftpsClient.storeFile(remoteFile, inputStream);
inputStream.close();
System.out.println("文件上传成功");
// 下载文件
String downloadFile = "remote-file.txt";
FileOutputStream outputStream = new FileOutputStream("downloaded-file.txt");
ftpsClient.retrieveFile(downloadFile, outputStream);
outputStream.close();
System.out.println("文件下载成功");
// 断开连接
ftpsClient.logout();
ftpsClient.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}