JAVA判断URL地址是否非法

 

 

 

/**
     * 判断请求url是否非法
     * @param url
     * @return
     */
    public static boolean isValidRequestUri(String url) {
        if (StringUtils.isNotEmpty(url)) {
            if (hasSpecialChar(url)) {
                return true;
            }
            try {
                /**尝试decode两次判断是否有特殊字符*/
                try {
                    /**URLDecoder: Incomplete trailing escape (%) pattern*/
                    url = url.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                    url = url.replaceAll("\\+", "%2B");
                    url = URLDecoder.decode(url, "utf-8");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                url = url.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                url = url.replaceAll("\\+", "%2B");
                url = URLDecoder.decode(url,"UTF-8");
                if(hasSpecialChar(url)){
                    return true;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            };

        }
        return false;
    }

    private static boolean hasSpecialChar(String url){
        return url.contains("<") || url.contains(">") || url.contains("\"")
                || url.contains("'")|| url.contains(" and ")
                || url.contains(" or ") || url.contains("1=1") || url.contains("(") || url.contains(")")
                || url.contains("{") || url.contains("}")|| url.contains("[") || url.contains("]");
    }

 

posted @ 2020-09-27 18:29  yvioo  阅读(2959)  评论(1编辑  收藏  举报