javaurlurihttpsurlconnection

URL to URI class cast exception


I had this code:

URL url = new URL(urlStr)
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

And is working correct until I updated to the latest spring/libraries versions. After that it showed me that this constructor new URL(String url) is deprecated in flavor of URI.toURL() to construct an instance of URL. I rewrite the code to:

Path path = Paths.get(urlStr);
URI uri = path.toUri();
HttpsURLConnection con = (HttpsURLConnection) uri.toURL().openConnection();

But it is throwing :

java.lang.ClassCastException: class sun.net.www.protocol.file.fileurlconnection cannot be cast to class javax.net.ssl.HttpsURLConnection (sun.net.www.protocol.file.fileurlconnection and javax.net.ssl.HttpsURLConnection are in module java.base of loader 'bootstrap')

So now i'm searching how to rewrite it to work again.


Solution

  • The Javadoc deprecation notice says "See the note on constructor deprecation for more details." And that note says that you can create your URL like this:

    URL url = URI.create(urlStr).toURL();
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    

    This works because every URL is a URI. Therefore you can pass a URL string to the URI constructor (or to the create() convenience method).

    Your previous attempt didn't work because Paths.get(urlStr) creates a Path which is specifically about files (typically on your local filing system), but https doesn't work with local files.