You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java程序上传文件至FTP时遭遇Connection refused错误求助

Fixing Java FTP Upload "Connection Refused" Error

Hey there, let's work through this java.net.ConnectException you're getting when trying to upload files via FTP with your Java code. I’ve looked over your snippet, and here are the most likely fixes to resolve the connection issue:

1. Verify FTP Server Reachability & Port Configuration

First, rule out basic network problems before diving into code tweaks:

  • Double-check your host variable: Make sure there are no typos, and if you’re using a domain name, confirm it resolves correctly to the server’s IP (use ping your-host to test).
  • Test port 21 connectivity with telnet your-host 21. If this command fails to connect, the issue isn’t in your code—it’s either the FTP server isn’t running on port 21, or network restrictions are blocking access.
  • Confirm the FTP server is actually listening on port 21: Some admins change the default port for security, so check your server’s FTP config to ensure you’re using the right port number.

2. Check Firewall & Security Group Rules

Connection refused errors often stem from firewall blocks:

  • Local Machine Firewall: Ensure your local firewall allows outbound traffic on port 21. Temporarily disable it (for testing) or add an exception rule for your Java application.
  • Server-Side Security/Firewall: If you’re using a cloud server (AWS, Azure, Alibaba Cloud, etc.), default security groups usually block inbound port 21. You’ll need to open port 21 for inbound traffic. Also, since you’re using passive mode (enterLocalPassiveMode()), the server uses a range of additional ports (typically 1024-65535)—make sure this port range is also open in the server’s firewall/security group.

3. Adjust Passive Mode & Connection Order

Your code uses passive mode, but the order of configuration might be causing issues. Try reordering your setup steps (login before setting passive mode is often more reliable):

public void upload(String localFile,String remoteFile) throws Exception{
    ftp = new FTPClient();
    ftp.setControlKeepAliveTimeout(300);
    
    ftp.connect(host, 21);
    // Check if connection was accepted
    if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
        ftp.disconnect();
        throw new Exception("FTP server rejected initial connection");
    }
    
    ftp.login(user, password);
    // Now set passive mode after login
    ftp.enterLocalPassiveMode();
    ftp.setUseEPSVwithIPv4(false);
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
    
    FileInputStream in = null;
    try {
        in = new FileInputStream(localFile);
        ftp.storeFile(remoteFile, in);
    } finally {
        if (in != null) {
            in.close();
        }
        if (ftp.isConnected()) {
            try {
                ftp.logout();
                ftp.disconnect();
            } catch (IOException e) {
                // Log or handle disconnect failure
            }
        }
    }
}
  • If passive mode still fails, try switching to active mode by replacing ftp.enterLocalPassiveMode() with ftp.enterLocalActiveMode(). Note that active mode may require your local machine to accept inbound connections, which can be blocked by firewalls.

4. Ensure Proper Resource Cleanup

While not the direct cause of connection refused, improper resource handling can lead to lingering connections that cause issues later. Wrapping your streams and FTP client operations in a finally block (like in the adjusted code above) ensures resources are released even if an error occurs.

Start with the network and firewall checks first—those are the most common culprits for connection refused errors. Once those are confirmed, tweak your code’s connection order and mode settings as needed.

内容的提问来源于stack exchange,提问作者Eithan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:17:46