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

前端 未结 2 1958
悲&欢浪女
悲&欢浪女 2021-01-02 00:01

I\'m working on a project where I\'m creating a class to run http client requests (my class acts as a client). It takes in a url and a request method (GET, POST, PUT, etc)

相关标签:
2条回答
  • 2021-01-02 00:23

    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();
    }
    
    0 讨论(0)
  • 2021-01-02 00:25

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

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    
    0 讨论(0)
提交回复
热议问题