springboot使用FTPClient连接报错:java.io.ioexception: connection is not open

在SpringBoot项目中使用FTPClient进行文件传输时遇到'connection is not open'异常。通过检查代码和配置,发现是由于FTP连接未正确建立或超时导致。解决方案包括检查FTP服务器的连接参数、设置合适的超时时间和确保在使用FTPClient对象前成功连接到服务器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
报错代码:

        FTPClient ftpClient = new FTPClient();
        ftpClient.setConnectTimeout(1000 * 30);//设置连接超时时间
        ftpClient.setControlEncoding("utf-8");//设置ftp字符集
        ftpClient.enterLocalPassiveMode();//设置被动模式,文件传输端口设置
        try {
            //设置文件传输模式为二进制,可以保证传输的内容不会被改变
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                LOGGER.error("connect ftp {} failed", host);
                ftpClient.disconnect();
                return null;
            }
            LOGGER.info("replyCode==========={}", replyCode);
        } catch (IOException e) {
            LOGGER.error("connect fail ------->>>{}", e.getMessage());
            return null;
        }
        return ftpClient;

解决办法

将 设置文件传输模式为二进制,可以保证传输的内容不会被改变 调整到登录之后
即将 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); 调整到 ftpClient.login(username, password); 后面
        FTPClient ftpClient = new FTPClient();
        ftpClient.setConnectTimeout(1000 * 30);//设置连接超时时间
        ftpClient.setControlEncoding("utf-8");//设置ftp字符集
        ftpClient.enterLocalPassiveMode();//设置被动模式,文件传输端口设置
        try {
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                LOGGER.error("connect ftp {} failed", host);
                ftpClient.disconnect();
                return null;
            }
            //设置文件传输模式为二进制,可以保证传输的内容不会被改变
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            LOGGER.info("replyCode==========={}", replyCode);
        } catch (IOException e) {
            LOGGER.error("connect fail ------->>>{}", e.getMessage());
            return null;
        }
        return ftpClient;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值