Java URL Decode urlDecode(String s)

Here you can find the source of urlDecode(String s)

Description

This utility method is for converting from a MIME format called "x-www-form-urlencoded" to a String

To convert to a String, each character is examined in turn:

  • The ASCII characters 'a' through 'z', 'A' through 'Z', and '0' through '9' remain the same.

    License

    Open Source License

    Declaration

    public static String urlDecode(String s) throws Exception 
    

    Method Source Code

    //package com.java2s;
    // are made available under the terms of the Eclipse Public License v1.0
    
    public class Main {
        /**//from   w  ww . j a  va  2s .c  o  m
        * This utility method is for converting from
        * a MIME format called "<code>x-www-form-urlencoded</code>"
        * to a <code>String</code>
        * <p>
        * To convert to a <code>String</code>, each character is examined in turn:
        * <ul>
        * <li>The ASCII characters '<code>a</code>' through '<code>z</code>',
        * '<code>A</code>' through '<code>Z</code>', and '<code>0</code>'
        * through '<code>9</code>' remain the same.
        * <li>The plus sign '<code>+</code>'is converted into a
        * space character '<code>&nbsp;</code>'.
        * <li>The remaining characters are represented by 3-character
        * strings which begin with the percent sign,
        * "<code>%<i>xy</i></code>", where <i>xy</i> is the two-digit
        * hexadecimal representation of the lower 8-bits of the character.
        * </ul>
        *
        */
        public static String urlDecode(String s) throws Exception {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                switch (c) {
                case '+':
                    sb.append(' ');
                    break;
                case '%':
                    try {
                        sb.append((char) Integer.parseInt(s.substring(i + 1, i + 3), 16));
                    } catch (NumberFormatException e) {
                        throw new IllegalArgumentException();
                    }
                    i += 2;
                    break;
                default:
                    sb.append(c);
                    break;
                }
            }
            // Undo conversion to external encoding
            String result = sb.toString();
            byte[] inputBytes = result.getBytes("8859_1"); //$NON-NLS-1$
            return new String(inputBytes);
        }
    }
    

    Related

    1. percentDecode(String str, boolean plusToSpace)
    2. safeDecode(String s)
    3. unescape(String s)
    4. unescape(String string)
    5. unescape(String theString)
    6. urlDecode(String scope)
    7. URLDecode(String str)
    8. urldecode(String str)
    9. urlDecode(String str)