解码包含百分比的字符串(%)

时间:2013-12-05 09:39:25

标签: java

我正在尝试解码包含(%)百分比的String,它正在抛出异常

Exception:URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "%&"

我的代码:

public class DecodeCbcMsg {

    public static void main(String[] args) throws UnsupportedEncodingException 
    {
        String msg="Hello%%&&$$";
        String strTMsg = URLDecoder.decode(msg,"UTF-8");
        System.out.println(strTMsg);
    }

3 个答案:

答案 0 :(得分:1)

看起来你的字符串编码不正确......

也许你应该确保它首先被正确编码?

例如,%的编码字符表示形式为%25 ...

所以请尝试解码Hello%25%25%26%26%24%24,然后看看你得到了什么:)

答案 1 :(得分:1)

你的msg不是有效的编码网址,因此无法解码。

就像您尝试解码无效的base64编码字符串一样。

PS: 来自URLDecoder代码

            case '%':
            /*
             * Starting with this instance of %, process all
             * consecutive substrings of the form %xy. Each
             * substring %xy will yield a byte. Convert all
             * consecutive  bytes obtained this way to whatever
             * character(s) they represent in the provided
             * encoding.
             */

            try {

                // (numChars-i)/3 is an upper bound for the number
                // of remaining bytes
                if (bytes == null)
                    bytes = new byte[(numChars-i)/3];
                int pos = 0;

                while ( ((i+2) < numChars) &&
                        (c=='%')) {
                    int v = Integer.parseInt(s.substring(i+1,i+3),16);
                    if (v < 0)
                        throw new IllegalArgumentException("URLDecoder: Illegal hex characters in escape (%) pattern - negative value");
                    bytes[pos++] = (byte) v;
                    i+= 3;
                    if (i < numChars)
                        c = s.charAt(i);
                }

                // A trailing, incomplete byte encoding such as
                // "%x" will cause an exception to be thrown

                if ((i < numChars) && (c=='%'))
                    throw new IllegalArgumentException(
                     "URLDecoder: Incomplete trailing escape (%) pattern");

                sb.append(new String(bytes, 0, pos, enc));
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException(
                "URLDecoder: Illegal hex characters in escape (%) pattern - "
                + e.getMessage());
            }

因此它尝试解析字符串%&amp;的int,它将抛出异常

答案 2 :(得分:0)

为了解码URL编码的字符串,首先需要对字符串进行url编码。在正确编码的URL中,%符号后面跟有两个十六进制数字0-9,A-F,因此URLDecoder会将您的%%视为非法。消息很清楚。确保正确编码您的URL。首先使用URLEncoder来编码你的msg字符串。