Java String Encode encode(final String s)

Here you can find the source of encode(final String s)

Description

Encode a string for inclusion in a URI (according to RFC 2396).

License

Mozilla Public License

Exception

Parameter Description
UnsupportedEncodingException an exception

Declaration

public static String encode(final String s)
        throws UnsupportedEncodingException 

Method Source Code

//package com.java2s;
/*/*from w  w  w. j av a  2  s.co m*/
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
 * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

import java.io.UnsupportedEncodingException;

public class Main {
    /**
     * Encode a string for inclusion in a URI (according to RFC 2396).
     * 
     * Unsafe characters are escaped by encoding them in three-character sequences '%xy', where 'xy' is the two-digit
     * hexadecimal representation of the lower 8-bits of the character.
     * 
     * The question mark '?' character is also escaped, as required by RFC 2255.
     * 
     * The string is first converted to the specified encoding. For LDAP (2255), the encoding must be UTF-8.
     * 
     * @throws UnsupportedEncodingException
     */
    public static String encode(final String s)
            throws UnsupportedEncodingException {
        final byte[] bytes = s.trim().getBytes("UTF-8");
        final int count = bytes.length;

        /*
         * From RFC 2396:
         * 
         * mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" reserved = ";" | "/" | ":" | "?" | "@" | "&" | "="
         * | "+" | "$" | ","
         */
        final String allowed = "=,+;.'-@&/$_()!~*:"; // '?' is omitted
        final char[] buf = new char[3 * count];
        int j = 0;

        for (int i = 0; i < count; i++) {
            if ((bytes[i] >= 0x61 && bytes[i] <= 0x7A) || // a..z
                    (bytes[i] >= 0x41 && bytes[i] <= 0x5A) || // A..Z
                    (bytes[i] >= 0x30 && bytes[i] <= 0x39) || // 0..9
                    (allowed.indexOf(bytes[i]) >= 0)) {
                buf[j++] = (char) bytes[i];
            } else {
                buf[j++] = '%';
                buf[j++] = Character.forDigit(0xF & (bytes[i] >>> 4), 16);
                buf[j++] = Character.forDigit(0xF & bytes[i], 16);
            }
        }
        return new String(buf, 0, j);
    }
}

Related

  1. encode(final String s)
  2. encode(final String s, final String encoding)
  3. encode(final String source, final String encoding, BitSet notEncoded)
  4. encode(String data, String encode)