I am trying to make an Https request in java with the below code snippet:
1. java.net.URL urlObject = new java.net.URL("/*my https url*/");
2. javax.net.ssl.HttpsURLConnection HttpsURLConnection = (javax.net.ssl.HttpsURLConnection)urlObject.openConnection();
At runtime in line2 the urlObject.openConnection()
returns an instance of sun.net.www.protocol.https.DelegateHttpsURLConnection
which is typecasted to javax.net.ssl.HttpsURLConnection
and this works perfectly fine.
However, in one of the environment this does not work and gives the below exception:
java.lang.ClassCastException: com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl cannot be cast to javax.net.ssl.HttpsURLConnection
Here in line 2 urlObject.openConnection()
returns an instance of com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl
which cannot be typecasted to javax.net.ssl.HttpsURLConnection
.
Can someone help me understand why urlObject.openConnection()
returns different instances of different classes in different environments. Is it something to do with the dependencies etc.
Additional Infos:
- I have read other stackoverflow answers regarding this. My objective here is to understand the underlying reason why this is happening which was not conveyed enough in other answers.
- One workarond I found was to use
com.sun.net.ssl.HttpsURLConnection con = (com.sun.net.ssl.HttpsURLConnection) urlObj.openConnection();
in place of line 2. Butcom.sun.net.ssl.HttpsURLConnection
is actually deprecated. - Another similar workaround was to use Http instead of Https i.e use
java.net.HttpURLConnection = (java.net.HttpURLConnection) urlObject.openConnection();
...but then this is does not answer my question about why the problem is actually happening. - I am using openJdk 8
Is there any particular reason you are trying to cast it to javax.net.ssl.HttpsURLConnection? You can use the base class, URLConnection and perform operations.