How to verify if a String in Java is a valid URL
JavaUrlJava Problem Overview
How can I check if a string is a URL in Java?
Java Solutions
Solution 1 - Java
You can try to create a java.net.URL
object out of it. If it is not a proper URL, a MalformedURLException
will be thrown.
Solution 2 - Java
You can use UrlValidator
from commons-validator. It will save you from writing code where the logic flow is guided by catching an exception, which is generally considered a bad practice. In this case, however, I think it's fine to do as others suggested, if you move this functionality to an utility method called isValidUrl(..)
Solution 3 - Java
For Android just add this line:
boolean isValid = URLUtil.isValidUrl( "your.uri" );
Solution 4 - Java
If you program in Android, you could use android.webkit.URLUtil
to test.
URLUtil.isHttpUrl(url)
URLUtil.isHttpsUrl(url)
Hope it would be helpful.
Solution 5 - Java
Here you go:
public static boolean isValidURL(String urlString) {
try {
URL url = new URL(urlString);
url.toURI();
return true;
} catch (Exception e) {
return false;
}
}
Solution 6 - Java
Complementing Bozho answer, to go more practical:
-
Download apache commons package and uncompress it.
-
Include commons-validator-1.4.0.jar in your java build path.
-
Test it with this sample code (reference):
//...your imports import org.apache.commons.validator.routines.*; // Import routines package! public static void main(String[] args){ // Get an UrlValidator UrlValidator defaultValidator = new UrlValidator(); // default schemes if (defaultValidator.isValid("http://www.apache.org")) { System.out.println("valid"); } if (!defaultValidator.isValid("http//www.oops.com")) { System.out.println("INvalid"); } // Get an UrlValidator with custom schemes String[] customSchemes = { "sftp", "scp", "https" }; UrlValidator customValidator = new UrlValidator(customSchemes); if (!customValidator.isValid("http://www.apache.org")) { System.out.println("valid"); } // Get an UrlValidator that allows double slashes in the path UrlValidator doubleSlashValidator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES); if (doubleSlashValidator.isValid("http://www.apache.org//projects")) { System.out.println("INvalid"); }
-
Run/Debug
Solution 7 - Java
This function validates a URL, and returns true (valid URL) or false (invalid URL).
public static boolean isURL(String url) {
try {
new URL(url);
return true;
} catch (Exception e) {
return false;
}
}
Be sure to import java.net.URL;
Solution 8 - Java
^(https://|http://|ftp://|ftps://)(?!-.)[^\\s/\$.?#].[^\\s]*$
This is a regex to validate URL for protocols http, https, ftp and ftps.