1. 程式人生 > 其它 >FTP連線方式,+忽略證書

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;
}
}