使用Java FTP连接到Localhost

时间:2016-04-11 15:59:46

标签: java ftp connection localhost

我正在开发JAVA的FTP程序。我正在使用Apache Commons Net Library。我的代码如下。

import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class ServerClass {
    private static void showServerReply(FTPClient ftpClient) {
        String[] replies = ftpClient.getReplyStrings();
        if (replies != null && replies.length > 0) {
            for (String aReply : replies) {
                System.out.println("SERVER: " + aReply);
            }
        }
    }
    public static void main(String[] args) {
        String server = "127.0.0.1";
        int port = 80;
        String user = "root";
        String pass = "root";
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(server, port);
            showServerReply(ftpClient);
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                System.out.println("Operation failed. Server reply code: " + replyCode);
                return;
            }
            boolean success = ftpClient.login(user, pass);
            showServerReply(ftpClient);
            if (!success) {
                System.out.println("Could not login to the server");
                return;
            } else {
                System.out.println("LOGGED IN SERVER");
            }
        } catch (IOException ex) {
            System.out.println("Oops! Something wrong happened");
            ex.printStackTrace();
        }
    }
}

但是我无法连接我的localhost。我想登录我的localhost并查看我的文件。 我的错误在下面。

Oops! Something wrong happened
java.net.ConnectException: Connection refused: connect
	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
	at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
	at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
	at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
	at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
	at java.net.PlainSocketImpl.connect(Unknown Source)
	at java.net.SocksSocketImpl.connect(Unknown Source)
	at java.net.Socket.connect(Unknown Source)
	at org.apache.commons.net.SocketClient.connect(SocketClient.java:188)
	at org.apache.commons.net.SocketClient.connect(SocketClient.java:209)
	at com.emrecanoztas.ftp.ServerClass.main(ServerClass.java:22)

你能帮助我吗?谢谢!..

2 个答案:

答案 0 :(得分:1)

问题:

  • 是否有FTP服务器正在运行?
  • FTP服务器日志中是否有关于连接请求的消息?
  • FTP服务器是否允许来自localhost的连接?
  • FTP服务器是否在localhost上侦听,或者您是否应该使用计算机的公共IP /名称? (查看netstat)

答案 1 :(得分:0)

尝试以下设置。

        String server = "ftp.icm.edu.pl";
        int port = 21;
        String user = "anonymous";
        String pass = "me@nowhere.com";