In java, how to create HttpsURLConnection or HttpU

2019-02-08 10:16发布

问题:

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?

回答1:

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

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


回答2:

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