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

2019-03-11 15:02发布

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

标签: java url
8条回答
时光不老,我们不散
2楼-- · 2019-03-11 15:15

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

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

Hope it would be helpful.

查看更多
手持菜刀,她持情操
3楼-- · 2019-03-11 15:18

For Android just add this line:

boolean isValid = URLUtil.isValidUrl( "your.uri" );
查看更多
乱世女痞
4楼-- · 2019-03-11 15:18

Here you go:

public static boolean isValidURL(String urlString)
{
    try
    {
        URL url = new URL(urlString);
        url.toURI();
        return true;
    } catch (Exception exception)
    {
        return false;
    }
}
查看更多
Rolldiameter
5楼-- · 2019-03-11 15:18

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

E.g

ResourceUtils.isUrl("https://stackoverflow.com/");
查看更多
一夜七次
6楼-- · 2019-03-11 15:19

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(..)

查看更多
孤傲高冷的网名
7楼-- · 2019-03-11 15:21

Complementing Bozho answer, to go more practical:

  1. Download apache commons package and uncompress it. binaries
  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

查看更多
登录 后发表回答