[ACCEPTED]-In java, how to create HttpsURLConnection or HttpURLConnection based on the url?-urlconnection

Accepted answer
Score: 35

HttpsURLConnection extends HttpUrlConnection, so you do not need the HttpsUrlConnection, you 1 can just do

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Score: 22

since HttpsURLConnection extends HttpURLConnection you can declare conn as HttpsURLConnection. In this way 4 you can access the common interface (setRequestMethod()).

In 3 order to access the extension methods (like 2 getCipherSuite(), defined only in the child class HttpsURLConnection) you 1 must use a cast after an instanceof:

if (conn instanceof HttpsURLConnection) {
    HttpsURLConnection secured = (HttpsURLConnection) conn;
    String cipher = secured.getCipherSuite();
}

More Related questions