What I want to achieve in my application is:
I have an account on ftp site like "filegenie.com" where i store some images.
Now I want to view those images when i start my application.
How can I do this in android? Can any one give me an head start into how those files should be accessed from the ftp site? I actually have no idea in this section. some simple tutorials, hints, examples are welcome.
My sole objective is to view images stored on filegenie.com from my android application
I have to do something similar with an FTP server I run off a destop. I downloaded a couple helper classes that are quite simple to use: FTP Classes Site
If you are using the android eclipse plugin open windows explorer and copy the jars into the "libs" folder in your project.
Here is a snipet of the type of code you would need:
import org.apache.commons.net.ftp.FTPClient;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(my.ip.com,port);
ftpClient.login(USERNAME, PASSWORD);
ftpClient.changeWorkingDirectory(PATH);
if (ftpClient.getReplyString().contains("250")) {
ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
BufferedInputStream buffIn = null;
buffIn = new BufferedInputStream(new FileInputStream(FULL_PATH_TO_LOCAL_FILE));
ftpClient.enterLocalPassiveMode();
boolean result = ftpClient.storeFile(FILENAME, buffIn);
buffIn.close();
ftpClient.logout();
ftpClient.disconnect();
}
} catch (SocketException e) {
System.err.print...
} catch (UnknownHostException e) {
System.err.print...
} catch (IOException e) {
System.err.print...
}
if(!result)
{.....}
Feel free to look through the FTPClient library
Related
I create small tracking app which get coordinates write them to xml file and then send this file with that data to ftp server. I am using function "SendFileGPS" to send that file but apk all the time crashes and it doesn't work. This function is using additional library common net 1.4 and it is quite strange because all the time when I start Android Studio I must download this library from web by Android Studio. And I got some additional questions.
I was thinking that maybe not only this function is a problem, how should look this server I mean how proper this server to get file from this app?
There is a another way to send this file without using additional libs ?
How it should look if I want send this file to another type of server (HTTPS)?
public void SendFileGPS()
{
FTPClient mFTP = new FTPClient();
try {
// Connect to FTP Server
mFTP.connect("here I put adress IP");
mFTP.login("here I put login", "here I put pass");
mFTP.setFileType(FTP.BINARY_FILE_TYPE);
mFTP.enterLocalPassiveMode();
// Prepare file to be uploaded to FTP Server
File file = new File("/path/to/MyXmlFileName.xml");
FileInputStream ifile = new FileInputStream(file);
// Upload file to FTP Server
mFTP.storeFile("filetotranfer",ifile);
mFTP.disconnect();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I'm new to android programming and ftp. Currently on a project to create android application to transfer file from PC to android device and verse vice. I'm able to transfer file from android device to PC using ftp server/client method. However, I'm facing difficulties on how to push file from PC to android device. Is it possible to push file from ftp server(PC) to client using ftp server/client? Or any alternatives to do so? Is there any tutorial/example which I could go through?
Any help would be greatly appreciated. Thanks a lot!
Transfer from android device to pc (android client side):
FTPClient mFTP = new FTPClient();
try {
// Connect to FTP Server
mFTP.connect("192.168.0.103");
mFTP.login("user", "password");
mFTP.setFileType(FTP.BINARY_FILE_TYPE);
mFTP.enterLocalPassiveMode();
File file = new File(f);
BufferedInputStream buffIn=null;
buffIn=new BufferedInputStream(new FileInputStream(file));
mFTP.enterLocalPassiveMode();
mFTP.storeFile(filename, buffIn);
buffIn.close();
mFTP.logout();
mFTP.disconnect();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
f.connect("ftp.drivehq.com",21);
if(f.login("XXXX", "XXX"))
{
f.enterLocalPassiveMode();
f.setFileType(FTP.BINARY_FILE_TYPE);
FileInputStream in = new FileInputStream(URL);
result = f.storeFile(newfile, in);
in.close();
f.logout();
f.disconnect();
}
It upload fine but not in particular path i also try as ftp://ftp.drivehq.com/myfolder
but it gives error in android unknown host exception like I need to upload file in particular folder So thanks in advance help me
Hi Please use the following code. it worked for me i have checked it.
SimpleFTP ftp = new SimpleFTP();
try
{
// Connect to an FTP server on port 21.
ftp.connect("host", 21, "username", "password");
// Set binary mode.
ftp.bin();
// Change to a new working directory on the FTP server.
ftp.cwd("/httpdocs/yourdestinationfolderinftp");
// Upload some files.
ftp.stor(new File("/mnt/sdcard/ftp.jpg"));
// Quit from the FTP server.
ftp.disconnect();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
I created an Android project on 2.3.3 and tried it on mobile 2.3.3, everything works OK. It didn't work on mobile 4, so I re-built for Android 4, but I have the same problem.
This is the code:
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();
}
}
}
Note:
I use commons-net-3.1 to connect.
In android version 2.3 above you can not start internet connection from main UI thread. Instead you should use AsyncTask. I assumed you are not using AsyncTask. If you are, then post the code and log cat also. Some examples of other operations that ICS and HoneyComb won't allow you to perform on the UI thread are:( from link posted in comment below ) -
Opening a Socket connection (i.e. new Socket()).
HTTP requests (i.e. HTTPClient and HTTPUrlConnection).
Attempting to connect to a remote MySQL database.
Downloading a file (i.e. Downloader.downloadFile()).
You should not use the main UI Thread to start a network connection or read/write data from it as #phazorRise explained it. But I strongly disagree with using an AsyncTask to perform your download. AsyncTask have been designed for short living operations and downloading a file doesn't belong to that category.
The most relevant way to achieve your goal, if your files are big (and I assume it depends on users, so we can say they are big) is to use a service to download the files.
I invite you to have a look at RoboSpice, it will give your app robustness for networking and it's really the most interesting library for network requests on Android.
Here is an inforgraphics to get familiarized with alternatives and understand why using a service is better than any other technology.
When I use "internet conections" programming for andoid 4, I do an Async Task as follows:
You can put this Class code into the same file as principal file to intercatue with global variables or functions.
public class MyAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String url = urls[0]
try {
//Connection request code, in your case ftp
} catch (Exception e) {
//Catch code
}
}
#Override
protected void onPostExecute(String result) {
//Code to de After the connection is done
}
}
Then, in the Activity I call the Asyn Task
String url = "http://...";
new MyAsyncTask().execute(url);
Edit
Here it's explained how to use Async Task, with an example
http://developer.android.com/reference/android/os/AsyncTask.html
I added this code, and all thing OK
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Note: I taked the code from #user1169115 comment in another post.
This isn't the best soluation, but I don't know why asynctask isn't work, so I don't have another choice.
I have a working ASP.NET Web API service running in Visual Studio on my dev box. I can easily get the proper results from either I.E. or FireFox by entering: http://localhost:61420/api/products. But when trying to read it from my Android Project using my AVD I get an exception thrown saying:
localhost/127.0.0.1:61420 - Connection refused.
I know my Android Java code works because I can access the WCF RESTFul service running on my Website (the URLthat's currently commented out). My Android code is pasted below.
So, why am I getting the error when accessing from my Eclipse project but not when accessing it from a browser?
Thanks
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpURLConnection urlConnection = null;
try
{
//URL url = new URL("http://www.deanblakely.com/myRESTService/SayHello");
URL url = new URL("http://localhost:61420/api/products");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String myString = readStream(in);
String otherString = myString;
otherString = otherString + " ";
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
urlConnection.disconnect();
}
}
private String readStream(InputStream is)
{
try
{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1)
{
bo.write(i);
i = is.read();
}
return bo.toString();
}
catch (IOException e)
{
return "" + e;
}
}
}
Visual Studio development web server will only accept connections from the local host and not over the network or other virtual connection. Sounds like AVD is seen as a remote host.
To access the app from anywhere, change the webserver that should be used. Assuming you're using Windows 7 and Visual Studio 2010, make sure you have IIS and all required features installed and set the local IIS as the webserver in your project settings:
It could be necessary to start Visual Studio as a Administrator to run it with local IIS.
Use the actual IP address of your machine ie, http://192.168.0.xx
Only your local machine can access localhost, and if you are on the emulator or a device, it will have a different IP through either NAT or your DHCP from the router.