FTPSClient javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake

 报错:

12:46:40.343 [main] INFO com.example.myproject.common.utils.FtpUtil - connecting...ftp服务器:127.0.0.1:21
12:46:41.444 [main] INFO com.example.myproject.common.utils.FtpUtil - connect successful...ftp服务器:127.0.0.1:21
12:46:41.444 [main] INFO com.example.myproject.common.utils.FtpUtil - 开始上传文件
12:46:41.448 [main] INFO com.example.myproject.common.utils.FtpUtil - 进入文件夹/ftp/ 成功!
12:46:41.483 [main] ERROR com.example.myproject.common.utils.FtpUtil - 上传文件失败
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
	at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:992)
	at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
	at org.apache.commons.net.ftp.FTPSClient._openDataConnection_(FTPSClient.java:646)
	at org.apache.commons.net.ftp.FTPClient._storeFile(FTPClient.java:653)
	at org.apache.commons.net.ftp.FTPClient.__storeFile(FTPClient.java:639)
	at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:2030)
	at com.example.myproject.common.utils.FtpUtil.uploadFile(FtpUtil.java:72)
	at com.example.myproject.common.utils.FtpUtil.uploadFileByFilePath(FtpUtil.java:100)
	at com.example.myproject.common.utils.FtpUtil.main(FtpUtil.java:194)
Caused by: java.io.EOFException: SSL peer shut down incorrectly
	at sun.security.ssl.InputRecord.read(InputRecord.java:505)
	at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
	... 10 more

先贴工具类看代码 参看原文Java 实现ftp 文件上传、下载和删除


@Slf4j
public class FtpUtil {
    //ftp服务器地址
    private String hostname;
    //ftp服务器端口号默认为21
    private Integer port;
    //ftp登录账号
    private String username;
    //ftp登录密码
    private String password;

    private SSLSessionReuseFTPSClient ftpsClient;

    public FtpUtil(String hostname, Integer port, String username,String password){
        this.hostname = hostname;
        this.port = port;
        this.username = username;
        this.password = password;
        this.initftpsClient();
    }

    /**
     * 初始化ftp服务器
     */
    private void initftpsClient() {
        ftpsClient = new SSLSessionReuseFTPSClient();
        ftpsClient.setControlEncoding("utf-8");
        try {
            log.info("connecting...ftp服务器:"+this.hostname+":"+this.port);
            ftpsClient.connect(hostname, port); //连接ftp服务器
            ftpsClient.login(username, password); //登录ftp服务器
            int replyCode = ftpsClient.getReplyCode(); //是否成功登录服务器
            if(!FTPReply.isPositiveCompletion(replyCode)){
                log.error("connect failed...ftp服务器:"+this.hostname+":"+this.port);
            }else {
                log.info("connect successful...ftp服务器:" + this.hostname + ":" + this.port);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean uploadFile( String pathname, String fileName,InputStream inputStream){
        boolean flag = false;
        try{
            log.info("开始上传文件");
            ftpsClient.setFileType(ftpsClient.BINARY_FILE_TYPE);
            ftpsClient.execPBSZ(0);
            ftpsClient.execPROT("P");
            ftpsClient.setControlEncoding("UTF-8");
            createDirecroty(pathname);
            ftpsClient.makeDirectory(pathname);
            ftpsClient.changeWorkingDirectory(pathname);
            ftpsClient.enterLocalPassiveMode();
            boolean v =ftpsClient.storeFile(fileName, inputStream);
            inputStream.close();
            ftpsClient.logout();
            flag = true;
            log.info("上传文件成功");
        }catch (Exception e) {
            log.error("上传文件失败");
            e.printStackTrace();
        }finally{
            if(ftpsClient.isConnected()){
                try{
                    ftpsClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    public boolean uploadFileByFilePath( String pathname, String fileName,String originFileName) throws FileNotFoundException {
        return uploadFile(pathname,fileName,new FileInputStream(new File(originFileName)));
    }
    
    public boolean uploadFileByFile( String pathname, String fileName,File file) throws FileNotFoundException {
        return uploadFile(pathname,fileName,new FileInputStream(file));
    }

    //改变目录路径
    public boolean changeWorkingDirectory(String directory) {
        boolean flag = true;
        try {
            flag = ftpsClient.changeWorkingDirectory(directory);
            if (flag) {
                log.info("进入文件夹" + directory + " 成功!");

            } else {
                log.error("进入文件夹" + directory + " 失败!开始创建文件夹");
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return flag;
    }

    //创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
    public boolean createDirecroty(String remote) throws IOException {
        boolean success = true;
        String directory = remote;
        // 如果远程目录不存在,则递归创建远程服务器目录
        if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            String path = "";
            String paths = "";
            while (true) {
                String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
                path = path + "/" + subDirectory;
                if (!existFile(path)) {
                    if (makeDirectory(subDirectory)) {
                        changeWorkingDirectory(subDirectory);
                    } else {
                        log.error("创建目录[" + subDirectory + "]失败");
                        changeWorkingDirectory(subDirectory);
                    }
                } else {
                    changeWorkingDirectory(subDirectory);
                }

                paths = paths + "/" + subDirectory;
                start = end + 1;
                end = directory.indexOf("/", start);
                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        }
        return success;
    }

    //判断ftp服务器文件是否存在
    public boolean existFile(String path) throws IOException {
        boolean flag = false;
        FTPFile[] ftpFileArr = ftpsClient.listFiles(path);
        if (ftpFileArr.length > 0) {
            flag = true;
        }
        return flag;
    }
    //创建目录
    public boolean makeDirectory(String dir) {
        boolean flag = true;
        try {
            flag = ftpsClient.makeDirectory(dir);
            if (flag) {
                log.info("创建文件夹" + dir + " 成功!");

            } else {
                log.error("创建文件夹" + dir + " 失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public static void main(String[] args) throws FileNotFoundException {
        FtpUtil ftpUtil = new FtpUtil("127.0.0.1",21,"admin","admin");
        ftpUtil.uploadFileByFilePath("/ftp/","xx.txt","f://xx.txt");
    }

}

解决 参看文章FTPClient TLS 与 FTP 进行数据传输异常:Remote host closed connection during handshake

How to connect to FTPS server with data connection using same TLS session?

我这里贴出来 配合刚刚的工具类

public class SSLSessionReuseFTPSClient extends FTPSClient {

    @Override
    protected void _prepareDataSocket_(final Socket socket) throws IOException {
        if (socket instanceof SSLSocket) {
            // Control socket is SSL
            final SSLSession session = ((SSLSocket) _socket_).getSession();
            if (session.isValid()) {
                final SSLSessionContext context = session.getSessionContext();
                try {
                    final Field sessionHostPortCache = context.getClass().getDeclaredField("sessionHostPortCache");
                    sessionHostPortCache.setAccessible(true);
                    final Object cache = sessionHostPortCache.get(context);
                    final Method method = cache.getClass().getDeclaredMethod("put", Object.class, Object.class);
                    method.setAccessible(true);
                    method.invoke(cache, String
                            .format("%s:%s", socket.getInetAddress().getHostName(), String.valueOf(socket.getPort()))
                            .toLowerCase(Locale.ROOT), session);
                    method.invoke(cache, String
                            .format("%s:%s", socket.getInetAddress().getHostAddress(), String.valueOf(socket.getPort()))
                            .toLowerCase(Locale.ROOT), session);
                } catch (NoSuchFieldException e) {
                    throw new IOException(e);
                } catch (Exception e) {
                    throw new IOException(e);
                }
            } else {
                throw new IOException("Invalid SSL Session");
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值