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

Adam Plumb picture Adam Plumb · Jun 3, 2009 · Viewed 44.7k times · Source

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?

Answer

Rob Di Marco picture Rob Di Marco · Jun 3, 2009

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

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