Android Apache Common FTP Open Source Library and HTTP differential analysis

Source: Internet
Author: User
Tags ftp client ftp protocol

1. Preface:

FTP Open Source Library: Apache Common FTP open Source Library upload files to the local area network FTP. The Open Source Library is Commons-net-2.2.jar. The package name is this: org.apache.commons.net.ftp.FTPClient; This framework can also be used to upload, download, and delete ftp server files. I am also referring to the online great God example quickly used in the project, now take the opportunity to summarize, as well as I have been on this basis again encapsulated FTP use class.

HTTP Open Source Library: Before the development of the first time using the HTTP protocol to upload files, delete files and so on, the use of Open Source Library is asynchttpclient Open source framework android-async-http. At that time I applied the scene also need to download files from the server, upload files, as well as delete files. Download the file, upload the file I used android-async-http this. The download is then used to download the file using the HttpURLConnection breakpoint continuation. Just put it together. Detailed connection: Android uses the asynchttpclient framework to upload files and use httpurlconnection to download files.

A simple Introduction to ftp: FTP is the abbreviation for file transportation Protocol (the Files Transfer Protocol). Currently on the Web, if you want to share files with others. The most convenient way is to put the file on the FTP server, and then other people through the FTP client program to download the required files. Like many other communication protocols, the FTP protocol also uses the client/server (Client/server) architecture. The user can connect to the FTP server through various FTP client programs, with the help of FTP protocol, to upload or download files. Typically, IP, port, username, and password are required.

HTTP is a simple introduction: HTTP is Hyper Text transportation Protocol (Hypertext Transfer Protocol) abbreviation. HTTP is a protocol that is designed to send content from Web servers located in various parts of the world to a non-specific majority of users. In other words, HTTP can be viewed as a protocol designed to "issue" files to a user who is not a specific majority. HTTP is used to read Web page content from the server. The Web browser downloads HTML files and image files from the Web server and temporarily saves them in the PC hard drive and memory for display. When you use HTTP to download content such as software, the difference is in whether it is saved as a Web browser display or in a way that is not displayed. The structure is exactly the same. Therefore, anyone can download the file as long as it is specified.

When I was developing, I was the developer of the server, defining the interface and the parameters that the interface needed to carry. I based on the interface to develop, I based on the interface to achieve the user's login, registration, get verification. and later upload files, delete server files and so on. Need parameters to see how the service has its side define the interface.

Here is the TCP/IP connection: In fact, the socket is the TCP/IP protocol encapsulation, the socket itself is not a protocol, but a call interface (API), through the socket, we can use the TCP/IP protocol. The TCP protocol corresponds to the transport layer. In the network transmission is also often used to a piece. Socket connection Open Source Library I didn't use it. It is generally self-written to be able to. If there is a good one, remember to leave the address of the comment.

2, re-encapsulated Customapacheftpmanage

Import Java.io.file;import java.io.fileinputstream;import java.io.fileoutputstream;import java.io.IOException; Import Java.io.inputstream;import java.io.outputstream;import java.sql.date;import Java.text.SimpleDateFormat; Import Java.util.linkedlist;import Org.apache.commons.net.ftp.ftpclient;import Org.apache.commons.net.ftp.ftpclientconfig;import Org.apache.commons.net.ftp.ftpfile;import Org.apache.commons.net.ftp.ftpreply;public class Customapacheftpmanage {public static String HostName = "";p ublic static int serverport = 1200;public static String userName = ""; public static string password = "";p rivate static ftpclient ftpclient = null;public static final string ftp_connect_succes SS = "Ftp_connect_successs";p ublic static final String ftp_connect_fail = "Ftp_connect_fail";p ublic static final string FT p_disconnect_success = "Ftp_disconnect_success";p ublic static final String ftp_file_notexists = "ftp_file_notexists"; public static final String ftp_upload_success = "ftp_upload_success";public static final String ftp_upload_fail = "Ftp_upload_fail";p ublic static final String ftp_upload_loading = "Ftp_upload _loading ";p ublic static final String ftp_down_loading =" ftp_down_loading ";p ublic static final String ftp_down_success =" Ftp_down_success ";p ublic static final String ftp_down_fail =" Ftp_down_fail ";p ublic static final string Ftp_deletefile_ SUCCESS = "Ftp_deletefile_success";p ublic static final String ftp_deletefile_fail = "Ftp_deletefile_fail";// For singleton mode public static customapacheftpmanage mcustomftpmanage = null;//Singleton mode get instance public static Customapacheftpmanage GetInstance () {if (Mcustomftpmanage = = NULL | | ftpclient = = NULL) {mcustomftpmanage = new customapacheftpmanage (); Ftpclie NT = new ftpclient ();} return mcustomftpmanage;} Public Customapacheftpmanage () {}public void Setparameter (String strhostname,int nserverport, String strUserName, String strpassword) {hostName = Strhostname;serverport = Nserverport;username = Strusername;password = strpassword;} // -------------------------------------------------------File Upload Method------------------------------------------------/** * Upload a single file. * * @param localfile * Local file * @param remotepath * FTP directory * @param listener * listener * @throw s ioexception */public void Uploadsinglefile (File singlefile, String Remotepath,currenttiplistener listener) throws IOException {//Before uploading this.uploadbeforeoperate (RemotePath, Listener); Boolean flag;flag = Uploadingsingle (singlefile , listener);//close connection This.uploadafteroperate (listener) after upload is complete;} /** * Upload multiple files. * * @param localfile * Local file * @param remotepath * FTP directory * @param listener * listener * @throw s ioexception */public void Uploadmultifile (linkedlist<file> fileList, String Remotepath,currenttiplistener Listener) throws IOException {//upload before initializing if (Uploadbeforeoperate (RemotePath, Listener)) {Boolean Flag;int n = 0;for (File s inglefile:filelist) {flag = Uploadingsingle (singlefile, listener); if (flag) {n ++;if (n = = Filelist.size ()) Listener.oncurrenttipcallback (ftp_upload_success);} else {listener.oncurrenttipcallback (ftp_upload_fail);}} Close connection this.uploadafteroperate (listener) after upload is complete;}; /** * Upload individual files. * * @param localfile * Local file * @return True upload succeeded, false upload failed * @throws IOException */private boolean Uploadingsin GLE (File Localfile,currenttiplistener listener) throws IOException {Boolean flag = true;//without a progress bar//Create input stream InputStream I Nputstream = new FileInputStream (localfile); Upload a single File flag = Ftpclient.storefile (Localfile.getname (), InputStream); Close file stream inputstream.close ();//The way//bufferedinputstream Buffin = new Bufferedinputstream (//new FileInputStream ( LocalFile));//progressinputstream progressinput = new Progressinputstream (Buffin,//listener, localFile);//flag = Ftpclient.storefile (Localfile.getname (), progressinput);//buffin.close (); return flag;} /** * Initialize relevant parameters before uploading a file * * @param remotepath * FTP directory * @param listener * listener * @throws IOException */p Rivate Boolean UploadbeforeopErate (String Remotepath,currenttiplistener listener) throws IOException {//Open FTP service try {this.openconnect (); Listener.oncurrenttipcallback (FTP_CONNECT_SUCCESSS);} catch (IOException E1) {e1.printstacktrace (); Listener.oncurrenttipcallback (Ftp_connect_fail); return false;} Set mode Ftpclient.setfiletransfermode (Org.apache.commons.net.ftp.FTP.STREAM_TRANSFER_MODE);// Create folder under FTP Ftpclient.makedirectory (RemotePath);//Change FTP directory Ftpclient.changeworkingdirectory (remotepath); return true;} /** * Close connection after upload is complete * * @param listener * @throws ioexception */private void uploadafteroperate (Currenttiplistener listener) Throws IOException {This.closeconnect ();} How to download-------------------------------------------------------file------------------------------------------------ /** * Download a single file for breakpoint download.            * * @param serverpath * FTP directory and file path * @param localPath * Local directory * @param fileName * File name after download * @param listener * listener * @throws ioexception */public void Downloadsinglefile (StringServerpath, String LocalPath, String fileName, Downloadprogresslistener listener) throws Exception {//Open FTP service try { This.openconnect (); listener.ondownloadprogress (ftp_connect_successs, 0, null);} catch (IOException E1) {e1.printstacktrace (); listener.ondownloadprogress (ftp_connect_fail, 0, NULL); return;} First determine if the server file exists ftpfile[] files = ftpclient.listfiles (Serverpath); if (files.length = = 0) {listener.ondownloadprogress ( ftp_file_notexists, 0, NULL); return;} Create local folder File Mkfile = new file (LocalPath), if (!mkfile.exists ()) {mkfile.mkdirs ();} LocalPath = LocalPath + filename;//then determine if the downloaded file can be breakpoint download long serversize = Files[0].getsize (); Gets the length of the remote file LocalFile = new file (localPath); Long localsize = 0;if (Localfile.exists ()) {localsize = Localfile.length ( ); If the local file exists, gets the length of the local file if (localsize >= serversize) {File File = new file (LocalPath); File.delete ();}} Progress long step = Serversize/100;long Process = 0;long CurrentSize = 0;//start preparing download file OutputStream out = new FileOutputStream (LocalFile, true); FtpcLient.setrestartoffset (localsize); InputStream input = Ftpclient.retrievefilestream (Serverpath); byte[] B = new byte[  1024];int length = 0;while (length = Input.read (b))! =-1) {out.write (b, 0, length); currentsize = CurrentSize + length;if (Currentsize/step! = Process)  {process = currentsize/step;if (process% 5 = = 0) {//per%5 Progress is returned once listener.ondownloadprogress (ftp_down_loading, process, null);}}} Out.flush (); Out.close (); Input.close ();//This method is to ensure that the stream is finished, and if this method is not present, it may cause the program to die if (Ftpclient.completependingcommand ()) { Listener.ondownloadprogress (ftp_down_success, 0, New File (LocalPath));} else {listener.ondownloadprogress (ftp_down_fail, 0, null);} After the download is complete, close the connection this.closeconnect (); listener.ondownloadprogress (ftp_disconnect_success, 0, NULL); return;} -------------------------------------------------------File Deletion method------------------------------------------------ /** * Delete files under FTP. * * @param serverpath * FTP directory and file path * @param listener * listener * @throws ioexception */public void dele TEsinglefile (String Serverpath, Deletefileprogresslistener listener) throws Exception {//Open FTP service try {this.openconnect ( ); listener.ondeleteprogress (FTP_CONNECT_SUCCESSS);} catch (IOException E1) {e1.printstacktrace (); listener.ondeleteprogress (ftp_connect_fail); return;} First determine if the server file exists ftpfile[] files = ftpclient.listfiles (Serverpath), if (files.length = = 0) {listener.ondeleteprogress (FTP _file_notexists); return;} Delete operation Boolean flag = True;flag = Ftpclient.deletefile (Serverpath); if (flag) {listener.ondeleteprogress (ftp_ deletefile_success);} else {listener.ondeleteprogress (ftp_deletefile_fail);} Close Connection This.closeconnect () after deletion is complete; listener.ondeleteprogress (ftp_disconnect_success); return;} -------------------------------------------------------Open the close connection------------------------------------------------ /** * Open the FTP service.  * * @throws ioexception */public void Openconnect () throws IOException {//Chinese transcoding ftpclient.setcontrolencoding ("UTF-8"); int Reply Server response value//Connect to Server Ftpclient.connect (HostName, ServerPort);/Get response Value reply = Ftpclient.getreplycode (); if (! Ftpreply.ispositivecompletion (Reply)) {//Disconnect ftpclient.disconnect (); throw new IOException ("Connect fail:" + Reply);} Log on to Server Ftpclient.login (userName, password);//Get response value reply = Ftpclient.getreplycode (); Ftpreply.ispositivecompletion (Reply)) {//Disconnect ftpclient.disconnect (); throw new IOException ("Connect fail:" + Reply);} else {//Get login information ftpclientconfig config = new Ftpclientconfig (Ftpclient.getsystemtype (). Split ("") [0]); Config.setserverlanguagecode ("zh"); ftpclient.configure (config);//Use passive mode to set the default Ftpclient.enterlocalpassivemode (); /binary file Support Ftpclient.setfiletype (Org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);}} /** * Turn off the FTP service. * * @throws ioexception */public void Closeconnect () throws IOException {if (ftpclient! = null) {//Exit Ftpftpclient.logout ();//Disconnect Ftpclient.disconnect ();}} ---------------------------------------------------upload, download, delete listening---------------------------------------------/* * Download Progress monitor */public interface DownloadprogresslisteNER {public void ondownloadprogress (String currentstep, long downprocess, file file);} /* * File Delete listener */public interface Deletefileprogresslistener {public void ondeleteprogress (String currentstep);} Public interface Currenttiplistener {public void Oncurrenttipcallback (String currentstep); Upload file Prepare public void Onuploadsfile (final linkedlist<file> upload,final Currenttiplistener listener) {// The FTP server needs a new folder name of final String Strftppath = "/" + getcurrentdatatime ("Yyyymmddhhmmss"); new Thread (New Runnable () {@ overridepublic void Run () {try {//file to be uploaded upload uploadmultifile (upload, Strftppath, listener);} catch (IOException e) {e.printstacktrace ();}}}). Start ();}      public string Getcurrentdatatime (string string) {Date date = new Date (System.currenttimemillis ());      SimpleDateFormat Sdformat = new SimpleDateFormat (string),///24-hour string lgtime = Sdformat.format (date);  return lgtime; }  }

Remember to join the permission to use the network.

Different connections, there are different transport protocols.

The code in this blog: click to download

3. Reference website

The difference between Android and server communication methods

Android Series Network (i)----Send HTTP requests using HttpClient (get data via get method)
FTP upload, download (with progress) in Android



Android Apache Common FTP Open Source Library and HTTP differential analysis

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.