ฉันต้องการให้คำตอบสำหรับกรณีที่คุณไม่สามารถควบคุมรหัสที่เปิดการเชื่อมต่อได้ เช่นเดียวกับที่ฉันทำเมื่อใช้URLClassLoaderเพื่อโหลดไฟล์ jar จากเซิร์ฟเวอร์ที่ป้องกันด้วยรหัสผ่าน
Authenticatorวิธีการแก้ปัญหาจะทำงาน แต่มีข้อเสียเปรียบที่มันเป็นครั้งแรกพยายามที่จะเข้าถึงเซิร์ฟเวอร์โดยไม่ต้องใช้รหัสผ่านและหลังจากเซิร์ฟเวอร์ขอรหัสผ่านให้เป็นหนึ่ง เป็นการไปกลับที่ไม่จำเป็นหากคุณรู้อยู่แล้วว่าเซิร์ฟเวอร์จะต้องใช้รหัสผ่าน
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;
}
}
สิ่งนี้จะลงทะเบียนโปรโตคอลใหม่myที่ถูกแทนที่ด้วยhttpเมื่อมีการเพิ่มข้อมูลรับรอง ดังนั้นเมื่อสร้างใหม่ให้URLClassLoaderแทนที่httpด้วยmyและทุกอย่างเรียบร้อยดี ฉันรู้ว่าURLClassLoaderมีตัวสร้างที่ใช้URLStreamHandlerFactoryแต่โรงงานนี้ไม่ได้ใช้หาก URL ชี้ไปที่ไฟล์ jar