Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Supporting both HttpURLConnection and HttpsURLConnection in the same variable?

Tags:

java

http

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?

like image 872
Rsaesha Avatar asked Feb 23 '26 12:02

Rsaesha


1 Answers

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.

like image 178
BalusC Avatar answered Feb 25 '26 02:02

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!