FTP on Android
package com.example.peble;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.UnknownHostException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class FtpActivity extends Activity {
static Uri currImageURI;
static TextView tv;
public void upload( String ftpServer, String user, String password,
String fileName, String source, String port ) throws MalformedURLException,
IOException
{
Toast.makeText(getApplicationContext(),
"pinging",
Toast.LENGTH_LONG).show();
int count = 0;
String str = "";
try {
Process process = Runtime.getRuntime().exec(
"/system/bin/ping -c 8 " + ftpServer);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
int i;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((i = reader.read(buffer)) > 0)
output.append(buffer, 0, i);
reader.close();
// body.append(output.toString()+"\n");
str = output.toString();
Toast.makeText(getApplicationContext(),
str,
Toast.LENGTH_LONG).show();
// Log.d(TAG, str);
} catch (IOException e) {
Toast.makeText(getApplicationContext(),
"exception in pingsystem",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"error in pingsystem",
Toast.LENGTH_LONG).show();
}
Toast.makeText(getApplicationContext(),
"trying inet",
Toast.LENGTH_LONG).show();
InetAddress in;
in = null;
// Definimos la ip de la cual haremos el ping
try {
in = InetAddress.getByName(ftpServer);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),
"unknown host " + e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"exception error unknown host " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
// Definimos un tiempo en el cual ha de responder
try {
if (in.isReachable(5000)) {
Toast.makeText(getApplicationContext(),
"is reachable",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"no response",
Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),
"exception " + e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"exception error is reachable" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
Toast.makeText(getApplicationContext(),
"uploading",
Toast.LENGTH_LONG).show();
if (ftpServer != null)
{
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
FTPClient fc= new FTPClient();
Toast.makeText(getApplicationContext(),
"uploading2 " + fc.toString() + ";"+ ftpServer + ":"+port + "inet address:" + InetAddress.getByName(ftpServer),
Toast.LENGTH_LONG).show();
// fc.connect(InetAddress.getByName(ftpServer));
fc.connect(InetAddress.getByName(ftpServer), Integer.parseInt(port));
// fc.connect("ftp://test:test@10.0.85.120:2121;type=i", 2121);
Toast.makeText(getApplicationContext(),
"uploading3",
Toast.LENGTH_LONG).show();
fc.login(user, password);
Toast.makeText(getApplicationContext(),
"uploading4",
Toast.LENGTH_LONG).show();
//fc.setFileType(FTP.BINARY_FILE_TYPE);
Toast.makeText(getApplicationContext(),
"uploading5",
Toast.LENGTH_LONG).show();
bis = new BufferedInputStream( new FileInputStream(
source) );
Toast.makeText(getApplicationContext(),
"uploading6",
Toast.LENGTH_LONG).show();
fc.storeFile(fileName, bis);
bis.close();
} catch (UnknownHostException e) {
Toast.makeText(getApplicationContext(),
"unknown host" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
catch (SocketException e) {
Toast.makeText(getApplicationContext(),
"socket exception" + e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),
"ioexception" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(),
"error here" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
finally
{
if (bis != null)
try
{
bis.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
if (bos != null)
try
{
bos.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
else
{
Toast.makeText(getApplicationContext(),
"error here2" ,
Toast.LENGTH_LONG).show();
}
}
/**
* Download a file from a FTP server. A FTP URL is generated with the
* following syntax:
* ftp://user:password@host:port/filePath;type=i.
*
* @param ftpServer , FTP server address (optional port ':portNumber').
* @param user , Optional user name to login.
* @param password , Optional password for user.
* @param fileName , Name of file to download (with optional preceeding
* relative path, e.g. one/two/three.txt).
* @param destination , Destination file to save.
* @throws MalformedURLException, IOException on error.
*/
public void download( String ftpServer, String user, String password,
String fileName, String destination, String port ) throws MalformedURLException,
IOException
{
if (ftpServer != null && fileName != null && destination != null)
{
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
FTPClient fc= new FTPClient();
// fc.connect(ftpServer, Integer.parseInt(port));
// fc.login(user, password);
// fc.setFileType(FTP.BINARY_FILE_TYPE);
bos = new BufferedOutputStream( new FileOutputStream(
destination) );
// fc.retrieveFile(fileName, bos);
bos.close();
// fc.deleteFile(fileName);
}
finally
{
if (bis != null)
try
{
bis.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
if (bos != null)
try
{
bos.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
else
{
System.out.println( "Input not available" );
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ftp);
}
// To handle when an image is selected from the browser, add the following to your Activity
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
// currImageURI is the global variable I’m using to hold the content:// URI of the image
Toast.makeText(getApplicationContext(),
"got currimage" ,
Toast.LENGTH_LONG).show();
currImageURI = data.getData();
Toast.makeText(getApplicationContext(),
"go currimageuri=" + currImageURI ,
Toast.LENGTH_LONG).show();
}
}
}
// And to convert the image URI to the direct file system path of the image file
public String getRealPathFromURI(Uri contentUri) {
// can post image
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/** Called when the user clicks the Select File button */
public void selectFile(View view) throws Exception {
Intent picIntent = new Intent();
picIntent.setType("image/*");
picIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(picIntent, "Select Picture"),1);
}
public void uploadFile(View view) throws Exception {
if (currImageURI != null)
Toast.makeText(getApplicationContext(),
"currImageURI=" + currImageURI.toString(),
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),
"calling upload" ,
Toast.LENGTH_LONG).show();
// upload("10.0.99.99", "test", "test", currImageURI.toString(), currImageURI.toString(), "2121" );
// upload("206.82.244.11", "test", "test", currImageURI.toString(), currImageURI.toString(), "2121" );
// upload("10.0.85.120", "test", "test", null, null, "2121" );
// upload("213.202.225.203", "test", "test", null, null, "2121" );
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
Toast.makeText(getApplicationContext(),
"starting async task",
Toast.LENGTH_LONG).show();
tv = (TextView) findViewById(R.id.uploadFilename);
if (tv != null) tv.setText("hello");
new DownloadWebpageTask().execute("test");
} else {
Toast.makeText(getApplicationContext(),
"not network",
Toast.LENGTH_LONG).show();
}
}
private class DownloadWebpageTask extends AsyncTask {
String result="";
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
InetAddress in;
in = null;
result += "entered doinbackground";
// Definimos la ip de la cual haremos el ping
try {
in = InetAddress.getByName("10.0.85.120");
result += ";in done";
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
result += ";not reachable5!" + e.getMessage();
} catch (Exception e) {
result += ";not reachable4!" + e.getMessage();
}
// Definimos un tiempo en el cual ha de responder
try {
if (in != null && in.isReachable(5000)) {
result += ";reachable!";
} else {
result +=";not reachable";
}
} catch (IOException e) {
// TODO Auto-generated catch block
result += ";not reachable!" + e.getMessage();
} catch (Exception e) {
result += ";not reachable2!" + e.getMessage();
}
FTPClient fc= new FTPClient();
try
{
fc.connect("10.0.85.120", 2121);
result += fc.getReplyString();
int reply = fc.getReplyCode();
result += "reply=" + reply;
if(!FTPReply.isPositiveCompletion(reply)) {
fc.disconnect();
result += "invalid reply code";
}
fc.enterLocalPassiveMode();
result += "local passive mode;connect sucess";
boolean b=fc.login("test", "test");
if (!b) {
result += ";login failed";
} else
result += ";login success";
if (fc.isConnected()) {
result += "; is connected";
FTPFile [] fileList=fc.listFiles();
reply = fc.getReplyCode();
fc.enterLocalPassiveMode();
result += "local passive mode;connect sucess";
result += "reply2=" + reply;
if(!FTPReply.isPositiveCompletion(reply)) {
fc.disconnect();
result += "invalid reply code2";
}
for(FTPFile f : fileList) {
result += ";" + f.getName();
}
}
result += ";disconnect";
fc.disconnect();
result +=";connect success";
} catch (Exception e) {
result += ";not reachable3!" + e.getMessage() + ";reply=" + fc.getReplyCode();
}
return result;
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
tv.setText(result);
}
}
}
No comments:
Post a Comment