简体   繁体   中英

FTP connection through proxy with Java

I'm trying to connect to an FTP server through a proxy using org.apache.commons.net.ftp.FTPClient. Pretty sure the system properties are getting set correctly as per following:

Properties props = System.getProperties();
props.put("ftp.proxySet", "true");
// dummy details
props.put("ftp.proxyHost", "proxy.example.server");
props.put("ftp.proxyPort", "8080");

Creating a connection raises a UnknownHostException which I'm pretty sure means the connection isn't making it past the proxy.

How can user credentials be passed through to the proxy with this connection type.

BTW, I can successfully create a URLConnection through the same proxy using the following; is there an equivalent for the Apache FTPClient?

conn = url.openConnection();
String password = "username:password";
String encodedPassword = new String(Base64.encodeBase64(password.getBytes()));
conn.setRequestProperty("Proxy-Authorization", encodedPassword);

How about using the FTPHTTPClient when you want to use a proxy;

if(proxyHost !=null) {
  System.out.println("Using HTTP proxy server: " + proxyHost);
  ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
}
else {
  ftp = new FTPClient();
} 

I think you need to use an Authenticator :

private static class MyAuthenticator extends Authenticator {
    private String username;
    private String password;
    public MyAuthenticator(String username, String password) {
        super();
        this.username = username;
        this.password = password;
    }
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password.toCharArray());
    }
}

public static void main(String[] args) {
    Authenticator.setDefault(new MyAuthenticator("foo", "bar"));
    System.setProperty("...", "...");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM