Android Url合法性校验

作者: 康熙微博私访记 | 来源:发表于2016-06-01 16:11 被阅读396次

    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

    相关文章

      网友评论

        本文标题:Android Url合法性校验

        本文链接:https://www.haomeiwen.com/subject/pvphdttx.html