使用 Java 通过代理进行 FTP 连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6606135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
FTP connection through proxy with Java
提问by ceej23
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:
我正在尝试使用 org.apache.commons.net.ftp.FTPClient 通过代理连接到 FTP 服务器。非常确定系统属性按以下方式正确设置:
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.
创建连接会引发 UnknownHostException,我很确定这意味着连接没有通过代理。
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?
顺便说一句,我可以使用以下方法通过相同的代理成功创建一个 URLConnection;Apache FTPClient 是否有等价物?
conn = url.openConnection();
String password = "username:password";
String encodedPassword = new String(Base64.encodeBase64(password.getBytes()));
conn.setRequestProperty("Proxy-Authorization", encodedPassword);
回答by Gabriel
How about using the FTPHTTPClient when you want to use a proxy;
当你想使用代理时,如何使用FTPHTTPClient;
if(proxyHost !=null) {
System.out.println("Using HTTP proxy server: " + proxyHost);
ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
}
else {
ftp = new FTPClient();
}
回答by MarcoS
I think you need to use an Authenticator
:
我认为你需要使用一个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("...", "...");
}