Android 平台下Ftp 使用模拟器需要注意的问题

本文介绍了一种在Android模拟器上使用FTPClient进行文件列表获取时遇到的问题及解决方案。在模拟器环境下,由于网络配置不同,需将FTP模式从主动模式更改为被动模式,以确保与服务器的正常连接和数据传输。

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

以下代码在pc上测试通过,可是在android模拟器上就不工作,不过还可以链接到服务器但不能得到文件 纠结了半天,原来是模式的问题,具体请Google 模拟器中采用建议被动模式

public void getWorkMessage(){  
      
      
    FTPClient ftp = new FTPClient();  
      
    try {  
        ftp.connect(server);  
          
        System.out.println("Connected to " + server);  
        System.out.print(ftp.getReplyString());  
  
        reply = ftp.getReplyCode();  
          
        if(!FTPReply.isPositiveCompletion(reply)) {  
            ftp.disconnect();  
            System.err.println("FTP server refused connection.");  
            System.exit(1);  
         }  
        ftp.login(username, password);  
          
        FTPFile[] files = ftp.listFiles("/");  
          
        if(files!=null&&files.length>0){  
              
            for(FTPFile f:files){  
                  
                System.out.println("user:>>>"+f.getUser()+" name:>>>"+f.getName()+" size:>>>"+f.getSize()+" link:>>>"+f.getLink());  
                  
            }  
        }  
    } catch (SocketException e) {  
          
        e.printStackTrace();  
    } catch (IOException e) {  
          
        e.printStackTrace();  
    }  
      
      
}  

 加上被动模式之后,代码如下:

public void getWorkMessage(){  
          
          
        FTPClient ftp = new FTPClient();  
          
        try {  
            ftp.connect(server);  
              
            System.out.println("Connected to " + server);  
            System.out.print(ftp.getReplyString());  
  
            reply = ftp.getReplyCode();  
              
            if(!FTPReply.isPositiveCompletion(reply)) {  
                ftp.disconnect();  
                System.err.println("FTP server refused connection.");  
                System.exit(1);  
             }  
            ftp.login(username, password);  
             
            //设置为被动模式  
           ftp.enterLocalPassiveMode();  
              
            FTPFile[] files = ftp.listFiles("/");  
              
            if(files!=null&&files.length>0){  
                  
                for(FTPFile f:files){  
                      
                    System.out.println("user:>>>"+f.getUser()+" name:>>>"+f.getName()+" size:>>>"+f.getSize()+" link:>>>"+f.getLink());  
                      
                }  
            }  
        } catch (SocketException e) {  
              
            e.printStackTrace();  
        } catch (IOException e) {  
              
            e.printStackTrace();  
        }  
          
          
    }  

OK,这样就可以了。

转载于:https://www.cnblogs.com/ToFlying/p/4158997.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值