TAGS :Viewed: 10 - Published at: a few seconds ago

[ Check format of URL ]

I need a Java code which accepts an URL like http://www.example.com and displays whether the format of URL is correct or not.

Answer 1


This should do what you're asking for.

public boolean isValidURL(String urlStr) {
    try {
      URL url = new URL(urlStr);
      return true;
    }
    catch (MalformedURLException e) {
        return false;
    }
}

Here's an alternate version:

public boolean isValidURI(String uriStr) {
    try {
      URI uri = new URI(uriStr);
      return true;
    }
    catch (URISyntaxException e) {
        return false;
    }
}

Answer 2


You can check the string with regular expression also.

Eg:

private static final String REGEX_URL = "^[A-Za-z][A-Za-z0-9+.-]{1,120}:[A-Za-z0-9/](([A-Za-z0-9$_.+!*,;/?:@&~=-])|%[A-Fa-f0-9]{2}){1,333}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*,;/?:@&~=%-]{0,1000}))?$";

String url = "http://www.example.com";
System.out.println(url.matches(REGEX_URL));

Courtesy for regex: http://www.manamplified.org/archives/2006/10/url-regex-pattern.html