Mysterious_android
Mysterious_android

Reputation: 618

HTTPS and HTTP connection in java

I know that HTTPS extends http. So does that mean i can do this?

HttpUrlConnection connect = passmyurl.openconnection(url);

and

HttpsUrlConnection connect = passmyurl.openconnection(url);



public static HttpsURLConnection passmyurl(URL url) throws IOException {
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        return connection;
    }

Does this mean that both will work? Since the HTTps extends HTTP, it means I can also pass a HTTP url to this function?

Upvotes: 2

Views: 7220

Answers (1)

dabaicai
dabaicai

Reputation: 999

In your code:

public static HttpsURLConnection passmyurl(URL url) throws IOException {
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    return connection;
}

You should change the return type HttpsURLConnection to URLConnection.Because the url.openConnection() result's type is subtype of URLConnection,and the exact type depends on the paramter url's protocol.The implemention document of openConnection() in the URL class:

If for the URL's protocol (such as HTTP or JAR), there exists a public, specialized URLConnection subclass belonging to one of the following packages or one of their subpackages: java.lang, java.io, java.util, java.net, the connection returned will be of that subclass. For example, for HTTP an HttpURLConnection will be returned, and for JAR a JarURLConnection will be returned.

So you can pass the Http url or Https url to your method.

See the following code:

    URLConnection httpConnection = new URL("http://test").openConnection();
    System.out.println(httpConnection.getClass());
    URLConnection httpsConnection = new URL("https://test").openConnection();
    System.out.println(httpsConnection.getClass());
    URLConnection ftpConnection = new URL("ftp://test").openConnection();
    System.out.println(ftpConnection.getClass());`

the print is:

class sun.net.www.protocol.http.HttpURLConnection
class sun.net.www.protocol.https.HttpsURLConnectionImpl
class sun.net.www.protocol.ftp.FtpURLConnection

Upvotes: 5

Related Questions