Bağlantıyı açan kod üzerinde kontrolünüzün olmadığı duruma bir cevap vermek istiyorum. URLClassLoaderParola korumalı bir sunucudan bir jar dosyasını yüklemek için kullanırken yaptığım gibi .
AuthenticatorÇözüm işe ama ilk şifre olmadan ve sadece şifre birini sağlayan sunucu sorar sonra sunucuyu ulaşmaya çalıştığı dezavantajı olacaktır. Sunucunun bir şifreye ihtiyaç duyacağını zaten biliyorsanız, bu gereksiz bir gidiş dönüş.
public class MyStreamHandlerFactory implements URLStreamHandlerFactory {
private final ServerInfo serverInfo;
public MyStreamHandlerFactory(ServerInfo serverInfo) {
this.serverInfo = serverInfo;
}
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {
switch (protocol) {
case "my":
return new MyStreamHandler(serverInfo);
default:
return null;
}
}
}
public class MyStreamHandler extends URLStreamHandler {
private final String encodedCredentials;
public MyStreamHandler(ServerInfo serverInfo) {
String strCredentials = serverInfo.getUsername() + ":" + serverInfo.getPassword();
this.encodedCredentials = Base64.getEncoder().encodeToString(strCredentials.getBytes());
}
@Override
protected URLConnection openConnection(URL url) throws IOException {
String authority = url.getAuthority();
String protocol = "http";
URL directUrl = new URL(protocol, url.getHost(), url.getPort(), url.getFile());
HttpURLConnection connection = (HttpURLConnection) directUrl.openConnection();
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
return connection;
}
}
Bu , kimlik bilgileri eklendiğinde mydeğiştirilen yeni bir protokolü kaydeder http. Yeni oluştururken Yani URLClassLoadersadece yerini httpile myve her şey yolunda. URLClassLoaderBir alan bir kurucu sağladığını biliyorum , URLStreamHandlerFactoryancak URL bir jar dosyasına işaret ediyorsa bu fabrika kullanılmıyor.