Decodes a urlencoded string into a byte array. - Java Internationalization

Java examples for Internationalization:Charset

Description

Decodes a urlencoded string into a byte array.

Demo Code

/*//from w ww.j a  v  a2 s.  c  o  m
 * Copyright (c) 2010 Matthew J. Francis and Contributors of the Bobbin Project
 * This file is distributed under the MIT licence. See the LICENCE file for further information.
 */
//package com.java2s;
import java.io.ByteArrayOutputStream;

public class Main {
    public static void main(String[] argv) throws Exception {
        String encodedString = "java2s.com";
        System.out.println(java.util.Arrays
                .toString(urldecode(encodedString)));
    }

    /**
     * Decodes a urlencoded string into a byte array. If the string is not a valid urlencoded
     * string, {@code null} is returned.
     *
     * @param encodedString The urlencoded string to decode
     * @return The decoded byte array, or {@code null}
     */
    public static byte[] urldecode(String encodedString) {

        char[] encodedChars = encodedString.toCharArray();

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        int i = 0;
        while (i < encodedChars.length) {
            if (encodedChars[i] == '+') {
                output.write(' ');
                i++;
            } else if (encodedChars[i] == '%') {
                if (i > encodedChars.length - 3) {
                    return null;
                }
                int x = Character.digit(encodedChars[i + 1], 16);
                int y = Character.digit(encodedChars[i + 2], 16);
                if ((x == -1) || (y == -1)) {
                    return null;
                }
                output.write((x << 4) + y);
                i += 3;
            } else {
                output.write(encodedChars[i]);
                i++;
            }
        }

        return output.toByteArray();

    }
}

Related Tutorials