How to pass https url to a class' constructor that requires URL object as parameter in Java?

850 Views Asked by At

Let's say I have a Java class, with one constructor that requires an java.net.URL object.

What can I do if the URL I want to initialize the constructor with is HTTPS?

2

There are 2 best solutions below

1
On BEST ANSWER
  String https_url = "https://www.google.com/";
  URL url;
  try {

     url = new URL(https_url);
     HttpsURLConnection con = (HttpsURLConnection)url.openConnection();

  } catch (MalformedURLException e) {
     e.printStackTrace();
  }

Source: http://www.mkyong.com/java/java-https-client-httpsurlconnection-example/

(...) As a result, if you attempt to construct a URL object with a string specifying HTTPS as the protocol, a MalformedURLException will be thrown.

Fortunately, to accommodate that constraint, the Java specification provides for the ability to select an alternate stream handler for the URL class.

Source: http://www.javaworld.com/article/2077600/learn-java/java-tip-96--use-https-in-your-java-client-code.html

0
On

You can initialize a new URL constructor using a representation with secure http just like any non-secure URL:

URL u = new URL("https://www.stackoverflow.com");

This will not throw MalformedURLException.

You can then pass your URL instance to your class' constructor.