- Реализация FTP-клиента на Java
- 1. Обзор
- 2. Настройка
- 3. Поддержка FTP в JDK
- 4. Подключение
- 5. Список файлов
- 6. Загрузка
- 7. Загрузка
- 8. Заключение
- Android Programming
- Monday, December 31, 2012
- Creating Android FTP client | FTP operations
- 38 comments:
- How to start FTP in Android
- Objective
- Step 1 Download Required .jar files.
- Step 2 MyFTPClientFunctions class
- Step 3 Call FTP Functions
- Tejas Jasani
Реализация FTP-клиента на Java
Узнайте, как легко взаимодействовать с внешним FTP-сервером на Java.
Автор: baeldung
Дата записи
1. Обзор
В этом уроке мы рассмотрим, как использовать Apache Commons Net библиотека для взаимодействия с внешним FTP-сервером.
2. Настройка
При использовании библиотек, которые используются для взаимодействия с внешними системами, часто рекомендуется написать несколько дополнительных интеграционных тестов, чтобы убедиться, что мы правильно используем библиотеку.
В настоящее время мы обычно используем Docker для запуска этих систем для наших интеграционных тестов. Однако, особенно при использовании в пассивном режиме, FTP-сервер не является самым простым приложением для прозрачного запуска внутри контейнера, если мы хотим использовать динамические сопоставления портов (что часто необходимо для выполнения тестов на общем сервере CI).
Вот почему мы будем использовать MockFtpServer вместо этого, поддельный/тупиковый FTP-сервер, написанный на Java, который предоставляет обширный API для удобного использования в тестах JUnit:
Рекомендуется всегда использовать последнюю версию. Их можно найти здесь и там .
3. Поддержка FTP в JDK
Удивительно, но в некоторых вариантах JDK уже есть базовая поддержка FTP в виде Удивительно, но в некоторых вариантах JDK уже есть базовая поддержка FTP в виде .
Однако мы не должны использовать этот класс напрямую, и вместо этого можно использовать JDK java.net. Класс URL как абстракция.
Эта поддержка FTP очень проста, но использует удобные API-интерфейсы java.nio.file.Файлы, этого может быть достаточно для простых случаев использования:
Поскольку в этой базовой поддержке FTP уже отсутствуют основные функции, такие как списки файлов, мы будем использовать поддержку FTP в библиотеке Apache Net Commons в следующих примерах.
4. Подключение
Сначала нам нужно подключиться к FTP-серверу. Давайте начнем с создания класса FTPClient.
Он будет служить в качестве API абстракции для реального FTP-клиента Apache Commons Net:
Нам нужен адрес сервера и порт, а также имя пользователя и пароль. После подключения необходимо проверить код ответа, чтобы убедиться, что соединение прошло успешно. Мы также добавляем PrintCommandListener , чтобы распечатать ответы, которые мы обычно видим при подключении к FTP-серверу с помощью инструментов командной строки в stdout.
Поскольку наши интеграционные тесты будут иметь некоторый шаблонный код, такой как запуск/остановка MockFtpServer и подключение/отключение нашего клиента, мы можем сделать это в методах @Before и @After :
Установив порт управления фиктивным сервером в значение 0, мы запускаем фиктивный сервер и свободный случайный порт.
Вот почему мы должны получить фактический порт при создании Ftp-клиента после запуска сервера, используя fakeFtpServer.getServerControlPort() .
5. Список файлов
Первым фактическим вариантом использования будет список файлов.
Давайте сначала начнем с теста в стиле TDD:
Сама реализация столь же проста. Чтобы сделать возвращаемую структуру данных немного проще для этого примера, мы преобразуем возвращаемый FTPFile массив преобразуется в список Строк с помощью Java 8 Потоков:
6. Загрузка
Для загрузки файла с FTP-сервера мы определяем API.
Здесь мы определяем исходный файл и место назначения в локальной файловой системе:
FTP-клиент Apache Net Commons содержит удобный API, который будет напрямую записывать данные в определенный выходной поток. Это означает, что мы можем использовать это напрямую:
7. Загрузка
MockFtpServer предоставляет некоторые полезные методы для доступа к содержимому своей файловой системы. Мы можем использовать эту функцию для написания простого интеграционного теста для функции загрузки:
Загрузка файла работает с точки зрения API очень похоже на его загрузку, но вместо использования OutputStream нам нужно предоставить InputStream вместо этого:
8. Заключение
Мы видели, что использование Java вместе с Apache Net Commons позволяет нам легко взаимодействовать с внешним FTP-сервером как для чтения, так и для записи.
Как обычно, полный код этой статьи доступен в нашем репозитории GitHub .
Источник
Android Programming
Monday, December 31, 2012
Creating Android FTP client | FTP operations
Many programmers have the following questions in mind.
«How do I do FTP operations from my android app?»
«How can I write a simple FTP client?»
«I want to store my application data in a FTP link at runtime. How can I do it?»
«How to upload images from my Android app to an FTP server/host ?»
There are many FTP client apps available for Android. But that’s not an in-app solution.
What I’m going to describe here is a very simple way to build an ftp client inbuilt into your app.
With this you would be able to download a file from ftp host / upload file to a ftp host etc.
1. You would need an ftp implementation. I use a library from apache commons project.
Copy org.apache.commons.net_2.0.0.v200905272248.jar file to the libs/ folder of your android app code
2. You would need an ftp host and an account to access it. I use drivehq.com.
drivehq.com provies 1 GB of free ftp space. All my sample codes are uploaded to the same ftp host.
Once you have an account you would have an UID & PW to access the host.
In the sample apps, I have mentioned it as FTP_UID and FTP_PW. Replace these with the actual uid&pw
3. Add permission to your Android manifest
Note: Do all the ftp operations on a separate thread. Do not block the UI thread.
All the following operations use the FTPClient class which is defined in the jar file.
The sample implementation can be found in my sample code: MyFTPClient.java
import import org.apache.commons.net.ftp.*;
Connecting to a FTP host
Disconnecting from a ftp host
Retrieving current FTP directory
Change the ftp directory path
Download a file from ftp host
Upload a file to an ftp host
Print files in list
Create a directory in ftp host
Remove a directory in ftp host
Remove a file in ftp host
Rename a file in ftp host
38 comments:
//Error: could not connect to host ftp.drivehq.com
Are you ale to connect to ftp.drivehq.com on the browser?
And where are you seeing this error?
I am not able to connect to ftp.drivehq.com and the error is shown in Eclipse Logcat. Please help.
Add Permision for Internet
This comment has been removed by the author.
This comment has been removed by the author.
salam syed kamal i need ur help can u help me plz
Hello;
I use the same code, but my probleme is that I can Upload and remove but I can’t download.
I tried to run Ftptest on Eclipse. However, «Login to ftp», «Upload file to ftp» and «Disconnect from ftp» did not work, just «Exit» was done. Can you help me.
Hi bess i m also doing the same code can u share ur id?
Hi, can someone upload complete ADT Eclipse Project Format.
Because its not running on my PC
Thanks
MANO whats your ID.
mahil post your id
Can anyone help how to count stream bytes while uploading and downloading a file. I have done my else coding, I will be grateful for your kind opinion.
Feel free to ask me for help in android
email ID: skystar.h8@gmail.com
I tried to run Ftptest on Eclipse. However, «Login to ftp», «Upload file to ftp» and «Disconnect from ftp» did not work, just «Exit» was done. Can you help me.
How to calculate progress while uploading and downloading, I am developing android FTP Client. Share your knowledge
hello syed kamal. i need ur help regarding android in my project..it includes obex ftp.
mahil143@yahoo.com
this is my ID MANO
please email me and contact me
syed kamal i need your help, please help in my project, i am unable to build this ftp project, my id is ameensvet@yahoo.com, or please give me your id.
thanks
very good work. Thank u)
But in my Eclipse your project show me many mistakes)
Can you help to solve this problem?
My mail once2go@ukr.net///\\\
i suppose you find a minutes for it)
with best regards, Denys Karpov
Hello Syed,
I am not able to connect to ftp server even same server is getting opened in browser.
I have add «INTERNET» permission in manifest file also.
The logcat displays below exception:
07-03 16:15:18.182: W/System.err(13827): java.net.UnknownHostException: Unable to resolve host «»: No address associated with hostname
07-03 16:15:18.182: W/System.err(13827): at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
07-03 16:15:18.182: W/System.err(13827): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
07-03 16:15:18.193: W/System.err(13827): at java.net.InetAddress.getByName(InetAddress.java:289)
07-03 16:15:18.193: W/System.err(13827): at org.apache.commons.net.SocketClient.connect(SocketClient.java:189)
07-03 16:15:18.193: W/System.err(13827): at org.apache.commons.net.SocketClient.connect(SocketClient.java:278)
07-03 16:15:18.193: W/System.err(13827): at com.kova.callmergeappinstaller.SendFiles$1.run(SendFiles.java:36)
07-03 16:15:18.193: W/System.err(13827): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
07-03 16:15:18.193: W/System.err(13827): at libcore.io.Posix.getaddrinfo(Native Method)
07-03 16:15:18.193: W/System.err(13827): at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:59)
07-03 16:15:18.193: W/System.err(13827): at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
07-03 16:15:18.193: W/System.err(13827): . 5 more
I tried to run Ftptest on Eclipse. However, «Login to ftp», «Upload file to ftp» and «Disconnect from ftp» did not work, just «Exit» was done. Can you help me.
Unfortunately, FtpTest has stoped
Sed kamal am facing this error when i press connect button of TestFtp
Please help me
please
i am student of MIT and my last semester goes to end after some days i have submit my project «SMART PHONE FTP CLIENT» and i have no idea about it
Please any one help me
I tried to run Ftptest on Eclipse. However, «Login to ftp», «Upload file to ftp» and «Disconnect from ftp» did not work, just «Exit» was done. Can you help me.
Источник
How to start FTP in Android
To download the code, login with one of the following social providers.
Login Login
Be patient. we are fetching your source code.
Objective
What is FTP ?
File Transfer Protocol (FTP) is a standard network protocol used to transfer files from one host to another host over a TCP-based network, such as the Internet. FTP is built on a client-server architecture and uses separate control and data connections between the client and the server. FTP users may authenticate themselves using a clear-text sign-in protocol, normally in the form of a username and password, but can connect anonymously if the server is configured to allow it.
For secure transmission that hides (encrypts) the username and password, and encrypts the content, FTP is often secured with SSL/TLS («FTPS»). SSH File Transfer Protocol («SFTP») is sometimes also used instead, but is technologically different.
Following are the steps to start FTP in Android device:
Step 1 Download Required .jar files.
First you need following JAR file:
1. commons-net-3.3.jar
Download latest jar file and add into libs folder of your Android project.
Step 2 MyFTPClientFunctions class
Create new class MyFTPClientFunctions into your project. Now add some FTP functions into newly created class.
- public FTPClient mFTPClient = null; // Add top of the class
Now add method to connect FTP server. (Method to connect to FTP server)
Now add method to disconnect FTP server. (Method to disconnect from FTP server)
Now add method to upload file on FTP server.
More methods are in full demo project.
Step 3 Call FTP Functions
Calling of above FTP functions. Create new class which extend Activity.
Add following into your class:
Now add following into onCreate:
For start FTP connection:
Every FTP connection call in new Thread
For terminate FTP connection:
If you have got any query related handling FTP in Android comment them below. Other FTP functions are in full demo project.
Got an Idea of Android App Development? What are you still waiting for? Contact us now and see the Idea live soon. Our company has been named as one of the best Android App Development Company in India.
Tejas Jasani
An entrepreneur who has founded 2 flourishing software firms in 7 years, Tejas is keen to understand everything about gaming — from the business dynamics to awesome designs to gamer psychology. As the founder-CEO of a company that has released some very successful games, he knows a thing or two about gaming. He shares his knowledge through blogs and talks that he gets invited to.
Источник