How to check URL format?

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:

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

Ram at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

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

James Jithin

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.