事实上,我从今天起就遇到了问题。我正在尝试在运行时通过 https url 动态加载 jar 文件 - 但我不知道如何准确地做到这一点。我可以通过标准 http: url 加载 jar,但在使用 https:
时则不行public void addURL(URL https) throws IOException {
HttpsURLConnection conn = (HttpsURLConnection) https.openConnection();
Class<?>[] parameters = new Class[]{URL.class};
log.info("https url : " + https);
// IMPORTANT: MUST use the webapp classloader - so derived extension classes car esolve their base classes
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
// cast to a URL class loader so we can additional JAR(s) to the search path
URLClassLoader webappClassLoader = (URLClassLoader)contextClassLoader;
Class<?> sysclass = URLClassLoader.class;
Method method;
try {
method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(webappClassLoader, new Object[]{ https });
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
非常感谢帮助:)指出/向我展示要添加的位置或内容等。
最佳答案
既然您正在处理安全连接,那么您就进入了证书领域。
Java 认为您的服务器不可信。您可以从堆栈跟踪中了解到这一点。
这里你有两个选择。您可以让您的程序忽略证书验证。在调用 addURL 之前,您只需执行此代码一次。
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.*;
private TrustManager[] getBypassingTrustManager()
{
TrustManager[] certs = new TrustManager[]
{
new X509TrustManager()
{
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String t)
{
}
public void checkServerTrusted(X509Certificate[] certs, String t)
{
}
}
};
return certs;
}
SSLContext sslCtx = SSLContext.getInstance("SSL");
TrustManager trustManager[] = getBypassingTrustManager();
sslCtx.init(null, trustManager, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());
从安全意义上来说,上述方法并不是很好。如果您了解 Java keystore 的工作原理 (java.security.KeyStore),效果会更好。您可以将服务器中的证书保存在 keystore 文件中,而不是忽略证书验证。然后,您的应用程序可以加载您的 keystore ,这使得 Java 信任您的服务器。
关于java - 将 jar 文件动态加载到 ClassPath - HTTPS url 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23514307/