Encodes a String using the set of characters allowed in a URI. - Java Network

Java examples for Network:URI

Description

Encodes a String using the set of characters allowed in a URI.

Demo Code

/**// w  ww.  ja  va 2 s .c om
 * Copyright (c) 2000-2016 Liferay, Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;

import java.io.UnsupportedEncodingException;

public class Main {
    private static final boolean[] sValidChar = new boolean[128];
    private static final char[] sHexLookup = new char[16];

    /**
     * Encodes a String using the set of characters allowed in a URI. This method encodes a multibyte string in UTF8
     *
     * @param   value  <code>String</code> to be translated.
     *
     * @return  the translated <code>String</code>.
     */
    public static String encodeUTF(String value) {
        String encodedValue = null;

        try {
            encodedValue = encode(value, "UTF8");
        } catch (UnsupportedEncodingException e) {
            // TODO - error handling
            // should never happen for this method because the
            // character encoding is constant
        }

        return encodedValue;
    }

    /**
     * Encodes a String using the set of characters allowed in a URI.
     *
     * @param      value     <code>String</code> to be translated.
     * @param      encoding  the Java alias for the character encoding to be used to convert non-ASCII characters into
     *                       bytes (e.g. <code>"UTF8"</code>).
     *
     * @return     the translated <code>String</code>.
     *
     * @exception  UnsupportedEncodingException  if the given encoding is not a recognised character encoding.
     */
    public static String encode(String value, String encoding)
            throws UnsupportedEncodingException {

        // Create a buffer that is roughly 1.5 times bigger than the value to
        // account for possible expansion of the resulting encoded string
        int len = value.length();
        StringBuilder out = new StringBuilder(len * 3 / 2);

        for (int charIndex = 0; charIndex < len; charIndex++) {
            char aChar = value.charAt(charIndex);

            if ((aChar <= 127) && sValidChar[aChar]) {
                out.append(aChar);
            } else if (aChar == ' ') {
                out.append('+');
            } else {
                byte[] charBytes = String.valueOf(aChar).getBytes(encoding);

                // For each byte to encode this character, write a '%',
                // followed by a 2 digit uppercase hex representation of the
                // byte value
                for (byte element : charBytes) {
                    out.append('%');

                    // Convert into two Hex digits (and don't worry about the
                    // sign bit, unlike Integer.toHexString()
                    out.append(sHexLookup[(element & 0xF0) >> 4]);
                    out.append(sHexLookup[element & 0x0F]);
                }
            }
        }

        // The result string should be encodable in pure ASCII
        return out.toString();
    }
}

Related Tutorials