在 Java 中连接到 FTP 服务器

本文实现了 Java 代码示例,这些示例展示了如何使用 Apache Commons Net 将您自己连接到 FTP 服务器并标识自己的身份。确保commons-net.jar文件存在于项目的 classpath.

The net.ftp.FTPClient 为通过 FTP 协议与服务器交互提供了必要的基础。要连接到服务器,请使用以下方法:

void connect(String server, int port):可以使用主机名或 IP 地址设置服务器,端口是用于侦听给定应用程序的传入连接的数字。FTP 使用端口 21.

连接后,使用此方法标识自己:

boolean login(String username, String password):此方法返回 true如果识别成功,否则 false.

调用 connect()

int responseFTP = clientFTP.getReplyCode();
if (!reponseFTP.isPositiveCompletion(replyCode)) {
// 操作失败。服务器拒绝
//连接或拒绝
返回操作;
}
每次方法调用后,服务器都会返回消息。以下方法显示来自服务器的消息:

private static void serverresponse(FTPClient ftpClient) {
String[] responses = ftpClient.getReplyStrings();
if (answers != null &&answers.length >0) {
for (String response: responses) {
System.out.println(SERVER: ” + response);
}
}
}
以下是包含登录、识别和验证的完整代码:

import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class FTPConnectionLogin {

private static void serverresponse(FTPClient ftpClient) {
String[] responses = ftpClient.getReplyStrings();
if (answers != null &&answers.length >0) {
for (String response: responses) {
System.out.println(SERVER: ” + response);
}
}
}

public static void main(String[] args) {
String server = serveraddress”;
int 端口 = 21;
字符串 username = username”;
字符串 password = password”;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
服务器响应(ftpClient);
int response = ftpClient.getReplyCode();
如果 (!FTPReply.isPositiveCompletion(response)) {
System.out.println(操作失败。服务器答案: + 答案);
返回;
}
boolean status = ftpClient.login(用户名,密码);
服务器响应(ftpClient);
if (!state) {
System.out.println(无法访问服务器”);
返回;
} else {
System.out.println(识别成功”);
}
} catch (IOException ex) {
System.out.println(检测到连接过程中的错误”);
例如 printStackTrace();
}
}
}
编译和执行:

SERVER: 220---------- 欢迎使用 Pure-FTPd [privsep] ----------
SERVER: 220-您是允许的 500 个用户中的 31 个。
SERVER: 220-本地时间现在是 06:02。服务器端口:21.
SERVER:220-这是一个私有系统 - 没有匿名登录
SERVER:220 您将在 3 分钟不活动后断开连接。
SERVER:230-OK。当前受限目录为 /
SERVER:已使用 230-100 个文件 (1%) - authorized:10000 files
SERVER:230 5217 KB 已用 (0%) - authorized:1536000 Kb
成功识别