Access FTP sever from android app - android

I can't access "ftp server in PC" from "android app" to download file, I used wireless connection.
public void FTP_Download(){
String server = "192.168.1.135";
int port = 21;
String user = "pc1";
String pass = "1551";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
Toast.makeText(getBaseContext(), "download starting.",Toast.LENGTH_LONG).show();
// APPROACH #1: using retrieveFile(String, OutputStream)
String remoteFile1 = "i.xml";
File downloadFile1 = new File("sdcard/i.xml");
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();
if (success) {
Toast.makeText(getBaseContext(), "File #1 has been downloaded successfully.",Toast.LENGTH_LONG).show();
}
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I added internet permission :
<uses-permission android:name="android.permission.INTERNET"/>
Note: I tested app in emulator on PC and all things was OK.
When I tried to access FTP from default browser I can't, but I can from firefox.
any help please

I've had the same issue. If it worked on the emulator and not on the device, there's probably a firewall in your way, or your network isn't allowing the connection because for some reason it's not secure enough. Also make sure your FTP server allows connections from your username and password.

Related

Android Socket connects to server but doesn't write anything

I'm currently runing a server on Eclipse(local IP 192.168.1.255, listening to port 4567). A client can connect trought sockets and send messages, that will be printed on the terminal by the server.
Part of the server code is the following:
System.out.println("Client connected: " + clientName);
String line;
while (true){
line = in.nextLine();
System.out.println("STRING RECEIVED: " + line + " FROM " + clientName);
}
where in is the input stream of the client socket.
Part of client code, instead, is:
while(true) {
System.out.print("\nEnter your input: ");
line = stdin.next();
socketOut.println(line);
socketOut.flush();
}
So, in example, a possible output on server terminal with two clients connected is the following:
Client connected: Socket[addr=/192.168.1.225,port=54852,localport=4567]
STRING RECEIVED: Hello FROM Socket[addr=/192.168.1.225,port=54852,localport=4567]
STRING RECEIVED: World FROM Socket[addr=/192.168.1.225,port=54852,localport=4567]
Client connected: Socket[addr=/192.168.1.225,port=54945,localport=4567]
STRING RECEIVED: Hello2 FROM Socket[addr=/192.168.1.225,port=54945,localport=4567]
Everything works well, so i'm now trying to access server trough sockets on a simple app developed on Android Studio. The code is:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new BackgroundTask().execute();
}
private class BackgroundTask extends AsyncTask {
#Override
protected Object doInBackground(Object[] params) {
try {
Socket socket = new Socket("10.0.2.2", 4567);
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println(new String("Hi from Android!"));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
But the output is just
Client connected: Socket[addr=/192.168.1.225,port=55001,localport=4567]
and nothing else.
Any advice about the println doesn't send anything? The program works perfectly on Eclipse on both client/server side, so i guess the problem is on Android. Also, i enabled the Android network permissions, so the connection should work.
Thanks in advance to everybody.
EDIT: solved, i just changed Android client code to:
try {
Socket socket = new Socket("10.0.2.2", 4567);
if (socket.isConnected()) {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
String line = new String("Hi from Android!");
out.println(line);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You need to either flush the PrintWriter or construct it to auto-flush. It doesn't by default.

Android FTP server authenticates once

I am trying to implement an FTP server in my application using the Apache FTP server library.
The server is up and running and working fine, but only once.
Note: I am using a hardcoded user for now. username: test and password: test
So in order:
App is launched, server is started, lets all FTP clients login.
App is killed by user.
App is started by user and server is started. Replies 530 authentication failed to user logging in with username: test and password: test
After that it responds with 530 authentication failed
My code below for making the server:
public void makePropertiesFile(){
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/user.properties");
if(file.exists() == false){
try {
file.createNewFile();
logMessage("user.properties File did not exist, made one");
properties = file;
this.addUsers();
} catch (IOException e) {
e.printStackTrace();
}
}
else {
logMessage("File already exists, no need to recreate");
userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile(properties);
userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());
org.apache.ftpserver.ftplet.UserManager userManager = userManagerFactory.createUserManager();
serverFactory.setUserManager(userManager);
}
}
public void addUsers(){
userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile(properties);
userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());
baseUser = new BaseUser();
baseUser.setName("test");
baseUser.setPassword("test");
baseUser.setHomeDirectory(Environment.getExternalStorageDirectory().getAbsolutePath());
baseUser.setEnabled(true);
List<Authority> authorities = new ArrayList<Authority>();
authorities.add(new WritePermission());
baseUser.setAuthorities(authorities);
org.apache.ftpserver.ftplet.UserManager userManager = userManagerFactory.createUserManager();
try {
userManager.save(baseUser);
} catch (FtpException e) {
e.printStackTrace();
logMessage("Could not save User");
}
serverFactory.setUserManager(userManager);
}
public void start(){
serverFactory = new FtpServerFactory();
listenerFactory = new ListenerFactory();
listenerFactory.setPort(port);
serverFactory.addListener("default",listenerFactory.createListener());
ftpServer = serverFactory.createServer();
this.makePropertiesFile();
try {
ftpServer.start();
logMessage("Started FTP server on port: " + port);
} catch (FtpException e) {
e.printStackTrace();
logMessage("Failed to start FTP server on port: " + port);
}
}
see this link http://androidexample.com/FTP_File_Upload_From_Sdcard_to_server/index.php?view=article_discription&aid=98&aaid=120
has a working project FTP with Android app

Can't connect to a computer on network running a server in java from my app

I am trying to connect a simple android client to a simple java server on another computer running on the same wi-fi network, i was able to connect with a java code(non android) on eclipse, and the server works just fine, but when i take the same code and put in my android app (android studio), it throws an IOException.
As of right now my protocol just returns a string "yay" and i just want to display it in a View.
My code:
private void createCom2(TextView showResult){
Socket pazeSocket = null;
PrintWriter pw = null;
BufferedReader br = null;
String ip = "10.0.0.4";
try {
pazeSocket = new Socket(ip, 4444);
pw = new PrintWriter(pazeSocket.getOutputStream());
br = new BufferedReader(new InputStreamReader(pazeSocket.getInputStream()));
} catch (UnknownHostException e) {
Toast.makeText(this,"Don't know about host: " + ip , Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this,"Couldn't get I/O for the connection to: " + ip , Toast.LENGTH_SHORT).show();
}
}
Thanks.
You need Internet permission for your app. Add this line to your manifest file:
<uses-permission android:name="android.permission.INTERNET"/>
and read more abut permissions here, if you like:
http://developer.android.com/guide/topics/manifest/manifest-intro.html

android not running on my phone, but on my emulator does

i wrote this ftp upload method...it works great on the emulator but doesnt on my phone...
can someone tell me why not?
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("ftp.atw.hu");
client.login("festivale", "festivale12");
Log.d("TravellerLog :: ", "Csatlakozva: ftp.atw.hu");
//
// Create an InputStream of the file to be uploaded
//
client.setFileType(FTP.BINARY_FILE_TYPE);
client.enterLocalPassiveMode();
String substr = globalconstant.path.substring(4, globalconstant.path.length());
String filename = substr + "/Festivale.db";
Log.e("TravellerLog :: ", substr + "/Festivale.db");
fis = new FileInputStream(filename);
//
// Store file to server
//
client.storeFile("Festivale.db", fis);
Log.d("TravellerLog :: ", "Feltöltve");
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
pls help i'm trying to do this ftp almost 3hours ago :S
On devices, you need to use a separate thread to handle the ftp connection.
"By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities."[android.developer.com/guide/components/services.html]

Android Uploading a file on ftp

Android file uploading issue
I am trying to upload image on my ftp server ,its not giving me any exception or error but image in nt deployed.Can anyone working on uploading image can identify problem.
FTPClient con = new FTPClient();
try{
con.connect("host",21);
con.login(username, pswd);
con.setFileType(FTP.BINARY_FILE_TYPE);
con.setFileTransferMode(FTP.ASCII_FILE_TYPE);
con.setSoTimeout(10000);
con.enterLocalPassiveMode();
if (con.login(username, pswd)) {
try {
File sFile = new File("mnt/sdcard/DCIM/download.jpg");
// connect.setText(sFile.toString());
BufferedInputStream buffIn = null;
buffIn = new BufferedInputStream(
new FileInputStream(sFile));
try {
String fileName = sFile.getName();
while (!dataUpResp) {
dataUpResp = con.storeFile(fileName,
buffIn);
// publishProgress("" + 10);
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.getMessage();
}
}
} catch (IOException e) {
}
Isn't it an issue that there are 2 times logging in in your code?
con.login(username, pswd); // 1st time
con.setFileType(FTP.BINARY_FILE_TYPE);
con.setFileTransferMode(FTP.ASCII_FILE_TYPE);
con.setSoTimeout(10000);
con.enterLocalPassiveMode();
if (con.login(username, pswd)) // 2nd time
Also you didn't use logout/disconnect for FTPClient and there are no flush and close for streams.
Tried your code with commons-net-3.2.jar with conjunctions of FileZilla FTP Server and it works fine.

Categories

Resources