我正在尝试通过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协议返回com.sun.net.ssl.internal.www.protocol.https.Handler
现在我知道javax的HttpsUrlConnection没有被返回但是com.sun.net.ssl.HttpsUrlConnection
非常感谢