13

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
  • 6
    Just define conn before the if statement. You need to read up on variable scope. Commented Dec 6, 2010 at 0:19

2 Answers 2

36

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

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Sign up to request clarification or add additional context in comments.

2 Comments

Problems exude with this in an age when HTTPS is becoming more and more required.
Yes, this is taking advantage of Java polymorphism. JVM will call method from appropriate class when using such conn. So type checking like if(is_https) doesn't make sense in this case. docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html
22

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.