Ftp客户端需要TSL功能
1、由于最近做了一个项目,需要把打包的文件传输到对方的FTP服务器上,但是用普通的java连接ftp客户端总是连接不上去,对方却说ftp客户端需要开通TSL功能。
直接上代码了!
package cn.tendency.LaibinGaFtp; import it.sauronsoftware.ftp4j.FTPClient; import java.io.File;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import org.apache.log4j.Logger; import cn.tendency.utils.FilesUtil; public class Test2 {
private static final Logger log = Logger.getLogger(Test2.class); public static void main(String[] args) {
putFile("111.59.53.333", 21, "wewe", "ddfaf", "E:\\houseTestData\\zip", "E:\\houseTestData\\back");
} public static void putFile(String host, int port, String username,
String password, String zipPath, String backPath) {
try {
TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
// TODO Auto-generated method stub } public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
// TODO Auto-generated method stub } public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
} } };
SSLContext sslContext = null;
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManager, new SecureRandom());
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
FTPClient client = new FTPClient();
client.setSSLSocketFactory(sslSocketFactory);
client.setSecurity(FTPClient.SECURITY_FTPES);
client.connect(host, 21);
log.info("连接111.59.53.18 ftp成功!"+client.toString());
client.login(username, password);
log.info("登录ftp成功!当前目录为:"+client.currentDirectory());
File file = new File(zipPath);
if (file.isDirectory()) {
log.info("我们读的是目录");
// 列出所有文件名
String[] files = file.list();
// 文件数
int fileNum = files.length;
log.info("文件夹下有" + fileNum + "个文件");
if (fileNum > 4) {
fileNum = 4;
}
for (int i = 0; i < fileNum; i++) {
File file2 = new File(file.getPath() + "\\" + files[i]);
try {
// FileInputStream input = new FileInputStream(file2);
client.upload(file2);
// boolean storeFile = client.storeFile(
// file2.getName(), input);
// input.close();
// 上传成功后备份压缩文件,不成功可以下次再传
// if (storeFile) {
// 备份
boolean flag1 = FilesUtil.copyFile2(file2,
backPath); if (flag1) {// 备份成功后删除文件;
log.info(file2+" 备份成功!"); file2.delete(); } else {
log.error(file2+" 备份成功!");
}
// } else {
// logger.error(file2.getName()+" 上传文件失败!");
// }
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
// Logout
client.logout(); log.info("退出ftp!");
// Disconnect
// ftpClient.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}