How to verify if a String in Java is a valid URL

2019-03-11 14:47发布

问题:

How can I check if a string is a URL in Java?

回答1:

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.



回答2:

You can use UrlValidator from commons-validator. It will save you from writing code where the logic flow is guided by caching 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(..)



回答3:

For Android just add this line:

boolean isValid = URLUtil.isValidUrl( "your.uri" );


回答4:

If you program in Android, you could use android.webkit.URLUtil to test.

URLUtil.isHttpUrl(url)
URLUtil.isHttpsUrl(url)

Hope it would be helpful.



回答5:

Complementing Bozho answer, to go more practical:

  1. Download apache commons package and uncompress it.
  2. Include commons-validator-1.4.0.jar in your java build path.
  3. 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");
    }
    
  4. Run/Debug



回答6:

Here you go:

public static boolean isValidURL(String urlString)
{
    try
    {
        URL url = new URL(urlString);
        url.toURI();
        return true;
    } catch (Exception exception)
    {
        return false;
    }
}


回答7:

For Spring Framework users. There is: org.springframework.util.ResourceUtils#isUrl

E.g

ResourceUtils.isUrl("https://stackoverflow.com/");


回答8:

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;



标签: java url