Rsaesha
Rsaesha

Reputation: 1114

Supporting both HttpURLConnection and HttpsURLConnection in the same variable?

I'm creating a class that handles HTTP connections, and I want to handle both HTTP and HTTPS but using the same variable (so I can just use the same code to send data, etc.) Currently, my code looks something like this:

if (ssl)
{
    conn = (HttpsURLConnection) new URL(...).openConnection();
    conn.setHostnameVerifier(...);
}
else
{
    conn = (HttpURLConnection) new URL(...).openConnection();
}

When "conn" is of type HttpsURLConnection, the HttpURLConnection cast fails. When "conn" is of type HttpURLConnection or URLConnection, the "setHostnameVerifier" and other HTTPS related methods are inaccessible.

Given that HttpsURLConnection is a subclass of the HttpURLConnection class, I'd have thought casting it would have worked, but I'm obviously mistaken. Is there any way of making this code work so that I can access HTTPS methods when I need them?

Upvotes: 3

Views: 7932

Answers (2)

gsjava
gsjava

Reputation: 131

Try this:

((HttpsURLConnection) new URL(...).openConnection()).setHostnameVerifier(...);

Upvotes: 1

BalusC
BalusC

Reputation: 1108642

Just keep conn an URLConnection and create a more specific local reference in the if block.

URLConnection conn;

// ...

conn = new URL(...).openConnection();

// ...

if (conn instanceof HttpsURLConnection) {
    HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
    httpsConn.setHostnameVerifier(...);
}

// ...

or just

// ...

if (conn instanceof HttpsURLConnection) {
    ((HttpsURLConnection) conn).setHostnameVerifier(...);
}

// ...

Keep in mind, in Java you're dealing with references, not with values. So no copies are created here.

Upvotes: 7

Related Questions