简体   繁体   中英

Https Website using HttpURLConnection

I have a question regarding using an HttpUrlConnection with a https web service.

Basically, we had previously written a bunch of web services to be used in an Android application that were all http calls. We want to change those over to use https instead. Basically, what I'm concerned with, is will my existing code work properly? I had previously created a connection like the following:

HttpURLConnection myConnection = (HttpURLConnection) myURL.openConnection();
myConnection.setConnectTimeout(TIMEOUT_MILLISEC);
myConnection.connect();

This appears to be working fine with the new https web services, but I'm wondering why I don't need to change it to something like this:

HttpsURLConnection myConnection = (HttpsURLConnection) myURL.openConnection();
myConnection.setConnectTimeout(TIMEOUT_MILLISEC);
myConnection.setSSLSocketFactory(createSSLSocketFactory());
myConnection.connect();

I'm still planning on moving to a HttpsURLConnection instead, but I'm curious how older versions of our app will be affected by our intended changes.

Thanks for the help!

In docs for HttpUrlConnection you will find:

Calling openConnection() on a URL with the "https" scheme will return an HttpsURLConnection

But since HttpsUrlConnection extends from HttpUrlConnection, this code:

HttpURLConnection myConnection = (HttpURLConnection) myURL.openConnection();

will NOT result in class cast exception if url is for https connection. You still can cast to HttpsUrlConnection - just for safety you can check with instanceof if url scheme should change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM