Android Url合法性校验

android.util.Patterns

/**
 *  Regular expression pattern to match most part of RFC 3987
 *  Internationalized URLs, aka IRIs.  Commonly used Unicode characters are
 *  added.
 */
public static final Pattern WEB_URL = Pattern.compile(
    "((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)"
    + "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_"
    + "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?"
    + "(?:" + DOMAIN_NAME + ")"
    + "(?:\\:\\d{1,5})?)" // plus option port number
    + "(\\/(?:(?:[" + GOOD_IRI_CHAR + "\\;\\/\\?\\:\\@\\&\\=\\#\\~"  // plus option query params
    + "\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?"
    + "(?:\\b|$)");

Url合法性校验方法

/**
 * 检查url的合法性
 * @param url
 * @return
 */
public static boolean checkUrl (String url) {
    if (Patterns.WEB_URL.matcher(url).matches()) {
        //符合标准url
        return true;
    } else{
        //不符合标准
        return false;
    }
}

实例

String url = "http://www.baidu.com\n";
LogUtil.i("checkurl:" + checkUrl(url));

output:false

String url = "http://www.baidu.com";
LogUtil.i("checkurl:" + checkUrl(url));

output:true
    原文作者:康熙微博私访记
    原文地址: https://www.jianshu.com/p/ee4a1f26013a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞