Java Reference
In-Depth Information
Does something seem familiar about this code? It is exactly the same code used to access
an HTTP URL that was introduced in Chapter 4 with the https URL instead. Java supports
HTTPS transparently. Simply pass an “https” based URL to any of the code used in this topic,
and HTTPS will be supported.
Understanding the HttpsURLConnection Class
So far every application in this topic 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 di-
rectly. 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:
try
{
URL u = new URL("https://www.httprecipes.com/1/5/https.php");
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 type-
cast 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.