连接失败:ftp connect中的ETIMEDOUT(连接超时)

时间:2014-09-17 09:13:54

标签: android ftp ftp-client

我一直在使用ftp在Android应用程序的服务器上传图像,我使用以下代码连接ftp。它在Wi-Fi上工作正常,但如果我切换到3G或2G连接,我会收到连接超时错误。那么请你告诉我如何处理这种情况。我的客户也在Veriozon,Sprint,ATT网络提供商也面临这个问题。它的iPhone版本在所有网络中运行良好。

代码:

try {
                    ftpClient = new FTPClient();
                    ftpClient.setConnectTimeout(30);
                    ftpClient.connect(InetAddress.getByName(server));

                    boolean isLogin = ftpClient.login(username, password);
                    boolean workingDir = ftpClient
                            .changeWorkingDirectory(path);

                    if (ftpClient.getReplyString().contains("250")) {

                        ftpClient
                                .setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);

                        buffIn = new BufferedInputStream(
                                new FileInputStream(filePath));
                        ftpClient.enterLocalActiveMode();
                        // ftpClient.enterLocalPassiveMode();

                        ProgressInputStream progressInput = new ProgressInputStream(
                                buffIn, progressHandler);

                        isUploaded = ftpClient.storeFile(fileName,
                                progressInput);

                        buffIn.close();
                        ftpClient.logout();
                        ftpClient.disconnect();
                    }

                } catch (Exception e) {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    progressDialog.dismiss();
                                    Toast.makeText(RegisterActivity.this,
                                            R.string.postimage_uploaderror,
                                            Toast.LENGTH_LONG).show();
                                }
                            });

                        }
                    });
                }

错误:

  

java.net.ConnectException:无法连接到主机(端口21):   连接失败:ETIMEDOUT(连接超时)

我已经导入" commons-net-ftp-2.0.jar"和commons-net-3.3.jar在我的项目中。

期待您的回答。

最诚挚的问候,

Devang

1 个答案:

答案 0 :(得分:0)

通常3G或2G连接比wifi慢,这就是连接超时错误的原因。要遇到这种情况,您需要为FTP客户端设置超时延迟,您可以通过添加此行

来实现
ftpClient.setConnectTimeout(30); // 30 mSeconds increase it for more time 

所以你的代码将成为:

ftpClient.setConnectTimeout(30);
ftpClient.connect(InetAddress.getByName(server));
boolean isLogin = ftpClient.login(username, password);
boolean workingDir = ftpClient.changeWorkingDirectory(path);

编辑

将超时时间增加到50秒(50000)

ftpClient.setConnectTimeout(50000); // 50 Seconds increase it for more time