Apache Commons Net FTPClient 默认使用被动模式。
以下是一个使用Apache Commons Net FTPClient的示例代码,其中使用被动模式连接FTP服务器:
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.IOException;
public class FTPExample {
public static void main(String[] args) {
FTPClient ftpClient = new FTPClient();
try {
// 连接FTP服务器
ftpClient.connect("ftp.example.com", 21);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("连接FTP服务器失败");
return;
}
// 登录FTP服务器
boolean success = ftpClient.login("username", "password");
if (!success) {
System.out.println("登录FTP服务器失败");
return;
}
// 切换到被动模式
ftpClient.enterLocalPassiveMode();
// 执行其他操作,如上传、下载文件等
// 断开连接
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的示例代码中,调用ftpClient.enterLocalPassiveMode()
方法切换到被动模式。如果要使用主动模式,可以调用ftpClient.enterLocalActiveMode()
方法切换到主动模式。