我正在尝试通过 Java Embedded Machine 连接到安全 http。
我在端口 8090 上运行自签名 apache 服务器。当我使用 Web 浏览器导航到https://myserver:8090
它时,会显示自签名证书警告并加载正常。
我有这个代码
URL dstUrl = new URL("https://myserver:8090")
URLConnection result = dstUrl.openConnection();
System.out.println("Protocol: "+dstUrl.getProtocol()+", is HTTPS:"+(result instanceof HttpsURLConnection));
// Echo: Protocol HTTPS is HTTPS:false
if (result instanceof HttpsURLConnection) {//will not reach
try {
HttpsURLConnection conn = (HttpsURLConnection) result;
conn.setSSLSocketFactory(sslContext.getSocketFactory());
conn.setHostnameVerifier(defaultHostVerifier);
} catch (Exception e) {
//sout will not ignate
}
}
return (HttpURLConnection) result;
此代码应该可以正常运行,但 openConecction() 将始终返回 HttpUrlConnection 而不是 HttpsUrlConnection。如果我知道该协议是 https,是否有机会强制打开 HttpsUrlConnection?
编辑:
我的进口:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
编辑2:
我在发行人网站上发现应该URLStreamHandlerFactory
在机器启动时应用,所以 https 协议由 deprecated 返回com.sun.net.ssl.internal.www.protocol.https.Handler
现在我知道 javax 的 HttpsUrlConnection 没有返回,而是返回com.sun.net.ssl.HttpsUrlConnection
不管怎么说,还是要谢谢你