Should I use uri.toURL().openConnection();
since URL is deprecated from java 20
Path path = Paths.get(apiUrl);
URI uri = path.toUri();
HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
So, is this a good way of establishing connection? If not then what are the other ways of doing this?
Should I use
uri.toURL().openConnection();
since URL is deprecated from java 20?
You seem to have a misconception. Class java.net.URL
is not deprecated. Only its constructors are. The API docs specifically recommend using URI.toURL() to obtain URL
instances, both in the class-level documentation and in each constructor's deprecation notice.
If the whole URL
class had been deprecated then URI.toURL()
would have been deprecated too. Even if somehow that had been missed, uri.toURL().openConnection()
still creates and uses a URL
object, which would be inadvisable if the whole class were in fact deprecated. But it's not.
You may use uri.toURL().openConnection()
to open a connection, provided the URI is suitable for that purpose. You may also use uri.toURL()
to obtain a reference to a URL
, store that or convey it to another location, and only later use it to open a connection:
URL url = uri.toURL();
// ...
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
I can't think of any form or amount of deprecation that would speak against one of those but not the other.