You are here

Understanding the HttpsURLConnection Class

    So far every application in this book has made use of either a direct InputStream or the HttpURLConnection class. There is also an HttpsURLConnection class, which is used for HTTPS sites. The HttpsURLConnection class subclasses the HttpURLConnection class. Because of this, your code does not need to be aware of if it receives an HttpsURLConnection or an HttpURLConnection object from your call to the openConnection function of a URL object.

    In some rare cases, you may want to make use of the HttpsURLConnection class directly. It does offer some additional functionality, not provided by the HttpURLConnection class. If you would like to make use of the HttpsURLConnection class, simply cast the result of the openConnection function. The following code opens a connection to a HTTPS site and retrieves an HttpsURLConnection class:

URL u = new URL("");
HttpsURLConnection http = u.openConnection();
// Now do something with the connection.
catch(MalformedURLException e)
System.out.println("Invalid URL");
catch(IOException e)
System.out.println("Error connecting: " + e.getMessage() );

    As you can see from above, the result of the openConnection function is typecast to an HttpsURLConnection. You should be careful, though. The above code will only work with HTTPS URLs. If you use an HTTP URL with the above code, you will get a ClassCastException thrown. This is because the openConnection function would return an HttpURLConnection, which cannot be typecast to an HttpsURLConnection.

    Code that was designed to work with HTTP can almost always work just as well with HTTPS; however, the opposite is not true.

    Using the HttpsURLConnection class directly gives you some additional information about the connection that would not be available with HttpURLConnection. For example, you can determine the cipher suite used by the server. In addition, you can get a list of all certificates used by the web server. Usually this information is unimportant to a bot. However, if you find that you need access to this data, you have the ability to use an HttpsURLConnection object.


Theme by Danetsoft and Danang Probo Sayekti inspired by Maksimer