Java: FTP with an HTTP proxy using the CONNECT method

There are many Linux based ftp clients, but if you run into connectivity issues when using the HTTP CONNECT method through a proxy such as Squid, you may need to leverage more control by writing your interactions using a library such as ftp4j.

In this article, I’ll provide a Java project with sample code that can CONNECT to an intermediary proxy like squid to communicate with an FTP server.

Prerequisites

In addition to having a JRE on the calling system, you also need to point to a proxy capable of passing through ftp commands using HTTP CONNECT.  I describe how to setup a Squid proxy for FTP passthrough in this article.

I have uploaded the code for this article on github.

FTP Connection via Proxy

The FTPConnectTest.java code has the critical pieces required to perform FTP operations via proxy.

First, the FTPClient must be set to use passive mode (reasons described here).

FTPClient client = new FTPClient();

client.setPassive(true);

Then an HTTPTunnelConnector needs to be created, specifying the HTTP proxy host and port that will be used as an intermediary.

HTTPTunnelConnector connector = new HTTPTunnelConnector(proxyHost,proxyPort);

client.setConnector(connector);

With this configuration set, you are now ready to make the connection using a set of credentials and can perform operations such as listing remote files and changing remote directories.

client.connect(ftpHost);
client.login(ftpUser, ftpPass);

// list files
FTPFile[] list = client.list();

// change directory
client.changeDirectory(changeDir);

For further examples, you can also look at FTPDeleteTest.java.

REFERENCES

http://www.sauronsoftware.it/projects/ftp4j/manual.php (docs)

https://github.com/eternnoir/ftp4j (github mirror of ftp4j)