我一直在尝试构建一个应用程序,该应用程序从用户那里捕获一些数据项,然后继续将其全部压缩成一个 zip 文件并通过 FTP 传输到服务器。压缩部分很有魅力,我相信 FTP 也会如此,只是程序拒绝连接到主机。
我已经尝试了所有的排列和组合来解决这个问题,但一直无法意识到问题所在。我已经包含了 apache commons net 库,并且能够将错误定位到连接部分。大部分代码已被注释掉,以便只允许使用其中的一部分。
我的代码是`package com.example.gis;
import java.io.FileInputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class FTP extends Activity {
public static FTPClient mFTPClient = null;
public String TAG="1234";
public static String a;
public static String b;
//public static int abc=FTP.BINARY_FILE_TYPE;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.ftp);
Bundle extras = getIntent().getExtras();
boolean m=ftpConnect("ftp://xxxxxxxxxx.xxx", "username omitted", "password omitted", 21);
if(m==true)
{
Toast.makeText(this,"FTP Login" , Toast.LENGTH_LONG).show();
a=extras.getString("path");
b=extras.getString("name");
ftpUpload("a", "b", "/test/");
ftpDisconnect();
}
else
Toast.makeText(this,"Failure to connect" , Toast.LENGTH_LONG).show();
}
public boolean ftpConnect(String host, String username,
String password, int port)
{
mFTPClient=new FTPClient();
try {
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
Toast.makeText(this,"Connected as status ="+status, Toast.LENGTH_LONG).show();
/* Set File Transfer Mode
*
* To avoid corruption issue you must specified a correct
* transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE,
* EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE
* for transferring text, image, and compressed files.
*/
mFTPClient.setFileType(abc);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch(Exception e) {
Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
public boolean ftpDisconnect()
{
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
Log.d(TAG, "Error occurred while disconnecting from ftp server.");
}
return false;
}
/**
* mFTPClient: FTP client connection object (see FTP connection example)
* srcFilePath: source file path in sdcard
* desFileName: file name to be stored in FTP server
* desDirectory: directory path where the file should be upload to
*/
public boolean ftpUpload(String srcFilePath, String desFileName,
String desDirectory)
{
boolean status = false;
try {
FileInputStream srcFileStream = new FileInputStream(srcFilePath);
// change working directory to the destination directory
if (ftpChangeDirectory(desDirectory)) {
status = mFTPClient.storeFile(desFileName, srcFileStream);
}
srcFileStream.close();
return status;
} catch (Exception e) {
Log.d(TAG, "upload failed");
}
return status;
}
}
已经有一段时间了。