简体   繁体   中英

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

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) and I want to be able to parse the URL and open a HttpsURLConnection or HttpURLConnection based on whether it is https or http (assume the given urls will always be correct).

If I do the following:

URLConnection conn = url.openConnection();

Then that will automatically create a URLConnection that can accept both http and https, but if I do this then I can't find any way to set a request method (GET, POST, etc), since only the HttpsURLConnection or HttpURLConnection classes have the setRequestMethod method.

If I do something like the following:

if(is_https)
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
else
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

Then the connections are created, but I can't access them outside of the if blocks.

Is it possible to do this, or should I just give up and use the apache httpclient classes?

HttpsURLConnection扩展了HttpUrlConnection ,所以你不需要HttpsUrlConnection,你可以做

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();
}

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