MxLDevs
MxLDevs

Reputation: 19526

How to set protocols to URI's without writing regex

I have an app that takes a user-input URL and fetches it. It must be a valid url with a protocol. However, the user may forget to include the protocol.

For example, when I go to this site I just type

stackoverflow.com

Instead of

http://stackoverflow.com

Because I know my browser will handle it for me anyways (along with auto-complete, so I usually only have to write stack)

So I go ahead

String lnk = "stackoverflow.com";
try {
  URL url = new URL(lnk);  
} catch (Exception e ) {
  e.printStackTrace();
}

But it throws an exception

java.net.MalformedURLException: no protocol: stackoverflow.com

Exploring the URL class, there is no setProtocol method either, so this might not help.

What should I use if I want to set protocols for input strings that may or may not have a protocol specified? I could do string scanning and checking manually.

Upvotes: 3

Views: 78

Answers (2)

M A
M A

Reputation: 72854

The URL class has a constructor that takes a protocol String as input:

URL.URL(String protocol, String host, String file)

e.g. URL url = new URL("http", "stackoverflow.com", "");

If a protocol needs to be added in case it is missing, the below snippet could be used for http and https:

if(!lnk.startsWith("http://") && !lnk.startsWith("https://")) {
    lnk = "http://" + lnk;
}

Upvotes: 3

Pankaj Sharma
Pankaj Sharma

Reputation: 679

You could check if it contains http or not using:

...
if(!lnk.startsWith("http://") {
   lnk = "http://" + lnk;
}

Hope this helps.

Upvotes: 2

Related Questions