Encodes an array of plain bytes into a urlencoded string - Java Internationalization

Java examples for Internationalization:Charset

Description

Encodes an array of plain bytes into a urlencoded string

Demo Code

/*/*w  ww .  j  av a 2  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;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] unencodedBytes = new byte[] { 34, 35, 36, 37, 37, 37, 67,
                68, 69 };
        System.out.println(urlencode(unencodedBytes));
    }

    /**
     * Encodes an array of plain bytes into a urlencoded string
     *
     * @param unencodedBytes The bytes to encode
     * @return A urlencoded string
     */
    public static String urlencode(byte[] unencodedBytes) {

        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < unencodedBytes.length; i++) {

            if (((unencodedBytes[i] >= 'a') && (unencodedBytes[i] <= 'z'))
                    || ((unencodedBytes[i] >= 'A') && (unencodedBytes[i] <= 'Z'))
                    || ((unencodedBytes[i] >= '0') && (unencodedBytes[i] <= '9'))
                    || (unencodedBytes[i] == '.')
                    || (unencodedBytes[i] == '-')
                    || (unencodedBytes[i] == '*')
                    || (unencodedBytes[i] == '_')) {
                buffer.append((char) unencodedBytes[i]);
            } else if (unencodedBytes[i] == ' ') {
                buffer.append('+');
            } else {
                buffer.append(String.format("%%%02x", unencodedBytes[i]));
            }

        }

        return buffer.toString();

    }
}

Related Tutorials