everyone,I am suffering this problem for 4 days..Help is needed…
I am developing an android program that intends to upload a file to a FTP server.
My developing environment: ubuntu12.04 + eclipse
I want to upload the file in a service. Now, the service can be started successfully.
here is the code of the upload method in service class.
public String ftpUpload(String url, String port, String username,String password,
String remotePath, String filePath,String fileName) {
FTPClient ftpClient = new FTPClient();
FileInputStream fis = null;
String returnMessage = "0";
try{
System.out.println("我看你能不能连接上!!!!");
ftpClient.connect(url,21);
System.out.println("我草还真能连上!!!!!!");
int reply = ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
ftpClient.disconnect();
System.err.println("FTP server refused connection.");
System.exit(1);
}
boolean loginResult = ftpClient.login(username, password);
int returnCode = ftpClient.getReplyCode();
Log.v("returnCode",""+returnCode);
System.out.println(loginResult);
if(loginResult && FTPReply.isPositiveCompletion(returnCode)){
ftpClient.listFiles("");
ftpClient.makeDirectory(remotePath);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
fis = new FileInputStream(filePath+"/"+fileName);
ftpClient.enterLocalPassiveMode();
System.out.println("last step!!!!!!");
ftpClient.storeFile("IwantYou", fis);
returnMessage = "1";
}
else
returnMessage = "0";
}
catch (IOException e){
e.printStackTrace();
throw new RuntimeException("擦,还真没连上!!!",e);
}
finally{
try{
ftpClient.disconnect();
}
catch(IOException e){
e.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
return returnMessage;
}
here is the problems:
test on android device: successful
test on emulator
-
if the emulator and the FTP server are not in the same computer:successful
-
if the emulator and the FTP server are in the same computer: fail
so let’s focus on this case..and some different options happens
-
if I connect real IP address(10.238.154.173) exception happens at
connect method, here is the logcat:W/System.err( 1074): org.apache.commons.net.ftp.FTPConnectionClosedException: Connection closed without indication. W/System.err( 1074): at org.apache.commons.net.ftp.FTP.__getReply(FTP.java:313) W/System.err( 1074): at org.apache.commons.net.ftp.FTP.__getReply(FTP.java:290) W/System.err( 1074): at org.apache.commons.net.ftp.FTP._connectAction_(FTP.java:392) W/System.err( 1074): at org.apache.commons.net.ftp.FTPClient._connectAction_(FTPClient.java:764) W/System.err( 1074): at org.apache.commons.net.SocketClient.connect(SocketClient.java:169) W/System.err( 1074): at org.apache.commons.net.SocketClient.connect(SocketClient.java:189) W/System.err( 1074): at com.example.hehe.FirstService.ftpUpload(FirstService.java:64) W/System.err( 1074): at com.example.hehe.FirstService$1.run(FirstService.java:36) W/System.err( 1074): at java.lang.Thread.run(Thread.java:841) I/System.out( 1074): something is wrong! W/System.err( 1074): java.lang.RuntimeException: 擦,还真没连上!!! W/System.err( 1074): at com.example.hehe.FirstService.ftpUpload(FirstService.java:94) W/System.err( 1074): at com.example.hehe.FirstService$1.run(FirstService.java:36) W/System.err( 1074): at java.lang.Thread.run(Thread.java:841) W/System.err( 1074): org.apache.commons.net.ftp.FTPConnectionClosedException: Connection closed without indication. W/System.err( 1074): at org.apache.commons.net.ftp.FTP.__getReply(FTP.java:313) W/System.err( 1074): at org.apache.commons.net.ftp.FTP.__getReply(FTP.java:290) W/System.err( 1074): at org.apache.commons.net.ftp.FTP._connectAction_(FTP.java:392) W/System.err( 1074): at org.apache.commons.net.ftp.FTPClient._connectAction_(FTPClient.java:764) W/System.err( 1074): at org.apache.commons.net.SocketClient.connect(SocketClient.java:169) W/System.err( 1074): at org.apache.commons.net.SocketClient.connect(SocketClient.java:189) W/System.err( 1074): at com.example.hehe.FirstService.ftpUpload(FirstService.java:64) W/System.err( 1074): ... 2 more -
if I connect the IP(10.0.2.2) I can connect successful.but the
storefile method failed.
I have google it for several days, all failed.
Any suggestion could be appreciated! Thanks!
org.apache.commons.net.ftp.FTPConnectionClosedException: Connection closed without indication.
Please follow the issue template and provide more details. issues like this do not provide any way of replicating the problem and spotting if it’s an Apache Commons FTP bug or an Android Upload Service bug. Thank you!
English is poor, please forgive me。
Using FTP to upload files to the window server was correct yesterday, but it went wrong today. The device system is android4.4.4
Sorry, but you have to follow what is in the issue template and provide necessary details, otherwise I couldn’t help you in any way
The same file, second pass will make mistakes ,and return «Error while uploading: xx to xx»
I don’t understand the code
try { String remoteFileName = getRemoteFileName(file); if (!ftpClient.storeFile(remoteFileName, localStream)) { throw new IOException("Error while uploading: " + file.getName(service) + " to: " + file.getProperty(PARAM_REMOTE_PATH)); } setPermission(remoteFileName, file.getProperty(PARAM_PERMISSIONS)); } finally { localStream.close(); }
The exception is thrown because the transfer of the file to your FTP directory is not possible. I don’t have the Apache Commons Net FTP docs at hand, but this may be due to permission policy for your FTP user or if the file already exists, in which case it doesn’t get overwritten.
Can you successfully upload the file for the first time? If I understand correctly, you get the exception only the second time you try to upload it.
Successfully upload the file for the first time.But,Some FTP servers can upload second times。
I’ll see if the FTP service is insufficient。
Example:
new FTPUploadRequest(mContext, _ip, _port)
.setUsernameAndPassword(_accout, _pwd)
.addFileToUpload(path, to)
.setNotificationConfig(config)
.setCreatedDirectoriesPermissions(new UnixPermissions(«777»))
.setSocketTimeout(301000)
.setConnectTimeout(301000)
Here it’s storeFile method JavaDoc. The method should overwrite the existing file the second time you try to make an upload.
The best way to check if the problem is in the library or in your FTP server config is to use one of the test FTP servers
You are right,this is FTP server Permission denied。
thanks
Я сделал небольшое приложение для Android, свое первое. Одна из его функций — загрузка текстовых отчетов на ftp-сервер. Я использую apache-commons-net. На некоторых устройствах ftp сервер закрывает соединение без индикации. Журналы сервера пусты.
Ниже приведен код внутреннего класса, выполняющего передачу файлов. Необходимо отправить четыре файла, отсюда и цикл. Элемент управления textViewResult используется для информирования пользователя о статусе передачи.
1. Видите ли вы, возможно, некоторые очевидные проблемы с кодом, которые могут привести к закрытому соединению?
2. Ошибка «соединение закрыто без индикации» ничего не говорит мне о реальном источнике проблемы. Есть ли способ получить более подробную информацию об ошибке?
Edit: Проблема была обнаружена на LG G5, H831, android 7.0. На LG H635 Android 6.0 работает без проблем.
Edit2: Stacktrace
Data uploading error:
Connection closed without indication.
Connection info:
MOBILE
UMTS
CONNECTED
Stack Trace:
org.apache.commons.net.ftp.FTP.getReply(FTP.java:324)
org.apache.commons.net.ftp.FTP.getReply(FTP.java:300)
org.apache.commons.net.ftp.FTP.connectAction(FTP.java:438)
org.apache.commons.net.ftp.FTPClient.connectAction(FTPClient.java:962)
org.apache.commons.net.ftp.FTPClient.connectAction(FTPClient.java:950)
org.apache.commons.net.SocketClient._connect(SocketClient.java:244)
org.apache.commons.net.SocketClient.connect(SocketClient.java:202)
com.jimmorr.t9a.t9amagicflux.ReportBattleResults$ConnectFTP.doInBackground(ReportBattleResults.java:555)
com.jimmorr.t9a.t9amagicflux.ReportBattleResults$ConnectFTP.doInBackground(ReportBattleResults.java:510)
android.os.AsyncTask$2.call(AsyncTask.java:304)
java.util.concurrent.FutureTask.run(FutureTask.java:237)
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
java.lang.Thread.run(Thread.java:761)
private class ConnectFTP extends AsyncTask<String, Void, String> {
private String resp;
ProgressDialog progressDialog;
protected Long doInBackground(String message) {
return null;
}
@Override
protected String doInBackground(String... strings) {
if (android.os.Debug.isDebuggerConnected())
android.os.Debug.waitForDebugger();
String server = "ftp....";
int port = 21;
String user = "user...";
String pass = "pass...";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
boolean success = ftpClient.changeWorkingDirectory("public_ftp/incoming");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
for (int j = 0; j<2;j++) {
for (int k = 0; k < 8; k = k + 2) {
OutputStream outputStream1;
Log.v(strings[k + 1]+" pass:"+j+" folder change:"+success, strings[k]);
outputStream1 = ftpClient.storeFileStream(strings[k + 1]);
outputStream1.write(strings[k].getBytes());
outputStream1.close();
if (j==0) resp = "main files sending :"+ k+"/4";
else resp = "backup files sending :"+ k+"/4";
if (!ftpClient.completePendingCommand()) {
ftpClient.logout();
ftpClient.disconnect();
System.err.println("File transfer failed.");
throw new IOException();
//System.exit(1);
}
}
success = ftpClient.changeWorkingDirectory("/public_ftp/back_up");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
}
return resp;
} catch (Throwable ex) {
progressDialog.dismiss();
String str = "Data uploading error:n" + ex.getMessage();
textViewResult.setText(str);
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
return null;
} catch (java.io.IOException ex) {
ex.printStackTrace();
Log.e("FTP connection",ex.getMessage());
}
return null;
}
//return null;
}
@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
progressDialog.dismiss();
}
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(ReportBattleResults.this,
"Sending Battle Report",
"sending data");
}
}
|
|
|
|

Следующие правила действуют в данном разделе в дополнение к общим Правилам Форума
1. Здесь обсуждается Java, а не JavaScript! Огромная просьба, по вопросам, связанным с JavaScript, SSI и им подобным обращаться в раздел WWW Masters или, на крайний случай, в Многошум.
2. В случае, если у вас возникают сомнения, в каком разделе следует задать свой вопрос, помещайте его в корневую ветку форума Java. В случае необходимости, он будет перемещен модераторами (с сохранением ссылки в корневом разделе).
3. Запрещается создавать темы с просьбой выполнить какую-то работу за автора темы. Форум является средством общения и общего поиска решения. Вашу работу за Вас никто выполнять не будет.
4. Не рекомендуется создавать несколько несвязанных вопросов в одной теме. Пожалуйста, создавайте по одной теме на вопрос.

apache commons-net. FTP
, не могу законнектиться
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
|
|
Простейший пример. Пытаюсь подсоединиться к локальному компу. Выбрасывает исключение. Где и что не так?
import java.io.*; import org.apache.commons.net.ftp.*; public class SortNumbers { public static void main(String[] args) throws IOException { FTPClient ftp = new FTPClient(); ftp.connect(«127.0.0.1»); FTPListParseEngine engine = ftp.initiateListParsing(«Temp»);//просмотр всех файлов в папке while (engine.hasNext()) { FTPFile[] files = engine.getNext(25); int lng = files.length; for (int i = 0; i < lng; i++) { String nameFile = files[i].getName(); System.out.println(nameFile); } } } } Такое вот исключение:
Exception in thread «main» java.net.ConnectException: Connection refused: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:364) at java.net.Socket.connect(Socket.java:507) at java.net.Socket.connect(Socket.java:457) at java.net.Socket.<init>(Socket.java:365) at java.net.Socket.<init>(Socket.java:178) at org.apache.commons.net.DefaultSocketFactory.createSocket(DefaultSocketFactory.java:53) at org.apache.commons.net.SocketClient.connect(SocketClient.java:162) at org.apache.commons.net.SocketClient.connect(SocketClient.java:250) at SortNumbers.main(SortNumbers.java:12) |
wind |
|
|
Moderator
Рейтинг (т): 269 |
В данном случае исключение говорит о том, что порт, по которому подключается клиент, никто не слушает. Попробуйте явно задать порт. |
|
Alita |
|
|
Цитата wind @ 24.04.07, 08:27 Попробуйте явно задать порт. В этом случае вывалилось:
Exception in thread «main» org.apache.commons.net.ftp.FTPConnectionClosedException: Connection closed without indication. at org.apache.commons.net.ftp.FTP.__getReply(FTP.java:267) at org.apache.commons.net.ftp.FTP._connectAction_(FTP.java:335) at org.apache.commons.net.ftp.FTPClient._connectAction_(FTPClient.java:550) at org.apache.commons.net.SocketClient.connect(SocketClient.java:163)
|
wind |
|
|
Moderator
Рейтинг (т): 269 |
А что в логах вашего ftp-сервера? Попытка соединения была? Кстати, что за сервер вы используете? |
|
Alita |
|
|
Все из-за невнимательности — проблема оказалась как раз в фтп сервере. Извиняюсь за беспокойство. |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- Java
- Следующая тема
[ Script execution time: 0,0232 ] [ 15 queries used ] [ Generated: 28.01.23, 17:31 GMT ]
RA FTP job fails with error «Connection closed without indication»
calendar_today
Updated On:
Products
CA Automic Workload Automation — Automation Engine
Issue/Introduction
Error Message :
com.uc4.ftpjob.DataTransferException: Connection exception.
Currently thread management with a wild card file transfer (FT) is implemented in a way that the FT terminates if one of the threads throws an exception. The Java standard thread pool is used.
Transferring multiple files in multiple threads uses the java.util.concurrent.ThreadPoolExecutor class. If the limit of connections is reached, there is a exception in one thread, that causes the whole ThreadPoolExecutor fail, the filetransfer stops with error:
com.uc4.ftpjob.DataTransferException: Connection exception.
at com.uc4.transfer.CITFTPImpl.<init>(CITFTPImpl.java:170)
at com.uc4.ftpjob.connections.ConnectionFactory$1.run(ConnectionFactory.java:75)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.apache.commons.net.ftp.FTPConnectionClosedException: Connection closed without indication.
at org.apache.commons.net.ftp.FTP.__getReply(FTP.java:317)
at org.apache.commons.net.ftp.FTP.__getReply(FTP.java:294)
at org.apache.commons.net.ftp.FTP.sendCommand(FTP.java:483)
at com.uc4.transfer.RAFTPClient.access$001(RAFTPClient.java:26)
at com.uc4.transfer.RAFTPClient$2.run(RAFTPClient.java:130)
at com.uc4.transfer.RAFTPClient$1.run(RAFTPClient.java:85)
… 1 more
The FTP Agent currently does not support to react on a connection failure within one single thread.
The implementation uses the «java.util.concurrent.ThreadPoolExecutor» class.
Reaching the limitation of concurrent connection on server side causes an exception in one of the threads which causes the whole TheradPoolExecutor to fail.
Current behavior is that Agent cannot reliably handle connection limitation on server side. This feature is not implemented.
Environment
OS Version: N/A
Cause
Cause type:
By design
Root Cause: The FTP Agent currently does not support to react on a connection failure within one single thread.
Resolution
The FTP Agent currently does not support to react on a connection failure within one single thread.
The implementation uses the «java.util.concurrent.ThreadPoolExecutor» class.
Reaching the limitation of concurrent connection on server side causes an exception in one of the threads which causes the whole TheradPoolExecutor to fail.
Fix Status: No Fix
Additional Information
Workaround :
The workaround is to work with a minimum set on threads. In every case lower than the server has configured taking into consideration that the server might have established connections from another client than the Agent.
Feedback
thumb_up
Yes
thumb_down
No
Moderator: Project members
-
chefjane
- 500 Command not understood
- Posts: 2
- Joined: 2009-09-25 16:20
- First name: Jane
- Last name: Brock
I can’t connect to server
#1
Post
by chefjane » 2009-09-25 16:37
I successfully downloaded filezilla, but I cannot connect to server. And repeatedly get an error message, cannot connect to server in red…..
The firewall is off and network connection is on/open..and working. All I want to do is post to my blog from my new laptop and cant.
Can someone help me? Please?
-
chefjane
- 500 Command not understood
- Posts: 2
- Joined: 2009-09-25 16:20
- First name: Jane
- Last name: Brock
Re: I can’t connect to server
#3
Post
by chefjane » 2009-09-30 17:39
Yes, I get message:
org.apache.commons.net.ftp.FTPconnection closed Exception connection closed without indication
If you can help I will be very grateful.
-
boco
- Contributor
- Posts: 26431
- Joined: 2006-05-01 03:28
- Location: Germany
Re: I can’t connect to server
#4
Post
by boco » 2009-10-01 11:41
org.apache.commons.net.ftp.FTPconnection closed Exception connection closed without indication
Don’t think it’s from FileZilla.
Please read Logs and post a log from FileZilla here. Do not modify anything (except username and password, if any).
### BEGIN SIGNATURE BLOCK ###
No support requests per PM! You will NOT get any reply!!!
FTP connection problems? Do yourself a favor and read Network Configuration.
FileZilla connection test: https://filezilla-project.org/conntest.php
### END SIGNATURE BLOCK ###




