HttpsURLConnectionOldImpl cannot be cast to javax.net.ssl.HttpsURLConnection

之前新建一个https连接是这样的:

URL urlStr = new URL("https", ip, Integer.parseInt(port), uri);
HttpsURLConnection conn = (HttpsURLConnection) (url).openConnection();

但是会偶发出现一个转换异常:com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl cannot be cast to javax.net.ssl.HttpsURLConnection

前几天发现该报错,查询资料得知:

这个构造函数来new 一个URL对象的话,url.openConnection()默认是返回com.sun.net.www.protocol.http.HttpURLConnection 类型对象。

解决办法:要加上一个URLStreamHandler 

URL urlStr = new URL("https", ip, Integer.parseInt(port), uri);  
URL url = new URL(null, urlStr.toString(), new Handler()); 
HttpsURLConnection conn = (HttpsURLConnection) (url).openConnection();

这个hanlder是在jdk自带jar包里面:import sun.net.www.protocol.https.Handler;

但很奇怪的是,并不是一定能复现,是偶发问题……

你可能感兴趣的:(java,ssl,.net,https)