3

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?

1
  • In most cases, you should keep the default host name verifier anyway. Commented Aug 1, 2012 at 16:08

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I was trying something like the second example you gave, but obviously I must have gotten the parentheses in the wrong place.
1

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.