FTP连接方式,+忽略证书


public static FTPSClient getFtpsClient(FtpConfigDto config) {
try {
FTPSClient ftpsClient = null;
//创建SSL上下文
SSLContext sslContext = SSLContext.getInstance("TLS");
//自定义证书,忽略已过期证书
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new miTM();
trustAllCerts[0] = tm;
//初始化
sslContext.init(null, trustAllCerts, null);

//创建客户端,加密选择Implicit
ftpsClient = new FTPSClient(true, sslContext);

ftpsClient.setAuthValue("TLS");
FTPClientConfig ftpClientConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
ftpClientConfig.setServerLanguageCode("de");
ftpsClient.configure(ftpClientConfig);
ftpsClient.setConnectTimeout(10*1000);
ftpsClient.setDataTimeout(18000);
ftpsClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
ftpsClient.connect(config.getHost(), config.getPort());
ftpsClient.execPROT("P");
//被动模式
ftpsClient.enterLocalPassiveMode();

ftpsClient.login(config.getUsername(), config.getPassword());

if (!FTPReply.isPositiveCompletion(ftpsClient.getReplyCode())) {
log.warn("FTP服务器拒绝连接");
//说明连接失败,需要断开连接
ftpsClient.disconnect();
} else {
log.info("FTP连接成功。");
}
ftpsClient.execPBSZ(0);

ftpsClient.setRemoteVerificationEnabled(false);
ftpsClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpsClient.setKeepAlive(true);
//被动模式
ftpsClient.enterLocalPassiveMode();
        
      

log.info("连接FTP服务器成功返回码 ==> {};ftpProperties:{}", ftpsClient.getReplyCode(), JSONObject.toJSONString(config));
return ftpsClient;
} catch (Exception e){
log.error("ftp连接异常:",e);
}
return null;
}





static class miTM implements TrustManager, X509TrustManager {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}

public boolean isServerTrusted(X509Certificate[] certs) {
return true;
}

public boolean isClientTrusted(X509Certificate[] certs) {
return true;
}

@Override
public void checkServerTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}

@Override
public void checkClientTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}
}



posted @ 2022-05-19 11:14  _最初  阅读(336)  评论(0编辑  收藏  举报