URLDecoder: Incomplete trailing escape (%) pattern错误处理

解码过程中可能会碰到url中含有普通的%字符的情况,如果直接用URLDecode.decode()则会出现如题的错误,解决方法就是先将’%’编码为’%25’,再对url解码。

 

1
2
3
4
5
6
public static void main(String[] args) throws Exception{
    String test = "http://www.baidu.com?123%";//随意构造的
    //URLDecoder.decode(test, "utf8");//如直接接就会报如题的错误。
    System.out.println(URLDecoder.decode(test.replaceAll("%", "%25"), "utf8"));
  
}

输出:

1
http://www.baidu.com?123%

上述是最简单的一种情况,但是绝大多数情况会掺杂着%为编码的含义,此时只把%替换为%25是不能解出正确的url的,如下:

1
2
3
4
public static void main(String[] args) throws Exception{
    String test = "http://www.baidu.com?%e4%b8%ad%e5%9b%bd123%";//%e4%b8%ad%e5%9b%bd为中国
    System.out.println(URLDecoder.decode(test.replaceAll("%", "%25"), "utf8"));
}

输出:

1
http://www.baidu.com?%e4%b8%ad%e5%9b%bd123%

解决方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class ConverPercent {
  
    //判断是否为16进制数
    public static boolean isHex(char c){
        if(((c >= '0') && (c <= '9')) ||
                ((c >= 'a') && (c <= 'f')) ||
                ((c >= 'A') && (c <= 'F')))
            return true;
        else
            return false;
    }
  
    public static String convertPercent(String str){
        StringBuilder sb = new StringBuilder(str);
  
        for(int i = 0; i < sb.length(); i++){
            char c = sb.charAt(i);
            //判断是否为转码符号%
            if(c == '%'){
                if(((i + 1) < sb.length() -1) && ((i + 2) < sb.length() - 1)){
                    char first = sb.charAt(i + 1);
                    char second = sb.charAt(i + 2);
                    //如只是普通的%则转为%25
                    if(!(isHex(first) && isHex(second)))
                        sb.insert(i+1, "25");
                }
                else{//如只是普通的%则转为%25
                    sb.insert(i+1, "25");
                }
  
            }
        }
  
        return sb.toString();
    }
  
    public static void main(String[] args) throws UnsupportedEncodingException{
        String test = "http://www.baidu.com?%e4%b8%ad%e5%9b%bd123%";
        //URLDecoder.decode(test, "utf8");//如直接接就会报如题的错误。  
        String url = convertPercent(test);
        System.out.println(url);
        System.out.println(URLDecoder.decode(url,"utf8"));
  
    }
}

输出:

1
2
http://www.baidu.com?%e4%b8%ad%e5%9b%bd123%25
http://www.baidu.com?中国123%

  

posted @   介寒食  阅读(1772)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示