In java, how to create HttpsURLConnection or HttpURLConnection based on the url?

廉价感情. 提交于 2019-11-30 11:39:15

HttpsURLConnection extends HttpUrlConnection, so you do not need the HttpsUrlConnection, you can just do

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

since HttpsURLConnection extends HttpURLConnection you can declare conn as HttpsURLConnection. In this way you can access the common interface (setRequestMethod()).

In order to access the extension methods (like getCipherSuite(), defined only in the child class HttpsURLConnection) you must use a cast after an instanceof:

if (conn instanceof HttpsURLConnection) {
    HttpsURLConnection secured = (HttpsURLConnection) conn;
    String cipher = secured.getCipherSuite();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!