Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding a String Containing Percentage(%)

Tags:

java

I am trying to decode a String that Contains (%) percentage, it's throwing an Exception

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

My Code:

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);
    }
like image 595
user2888996 Avatar asked Dec 05 '13 09:12

user2888996


2 Answers

It doesn't look like your string is encoded correctly...

Maybe you should ensure it is properly encoded first?

For example, the encoded character representation for % is %25...

So please try decoding Hello%25%25%26%26%24%24 instead, and see what you get :)

like image 175
vikingsteve Avatar answered Oct 31 '22 10:10

vikingsteve


your msg is not a valid encoded url, so it cannot be decode.

just like you try to decode a invalid base64 encode string.

ps: from URLDecoder code

            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());
            }

so it try to parse int of string %&, it will throw exception

like image 34
andy Avatar answered Oct 31 '22 12:10

andy