Java String Decode by Charset decode(String s, Charset encoding)

Here you can find the source of decode(String s, Charset encoding)

Description

Decodes an octet according to RFC 2396.

License

Apache License

Parameter

Parameter Description
s the URI to decode
encoding the encoding to decode into

Return

The decoded URI

Declaration

public static String decode(String s, Charset encoding) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.nio.charset.Charset;

public class Main {
    public static final Charset LATIN1 = Charset.forName("ISO-8859-1");

    /**/*  ww  w  .java 2s  .co  m*/
     * Decodes an octet according to RFC 2396. According to this spec,
     * any characters outside the range 0x20 - 0x7E must be escaped because
     * they are not printable characters, except for any characters in the
     * fragment identifier. This method will translate any escaped characters
     * back to the original.
     *
     * @param s      the URI to decode
     * @param encoding the encoding to decode into
     * @return The decoded URI
     */
    public static String decode(String s, Charset encoding) {
        if (s == null || s.isEmpty()) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        boolean fragment = false;
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            switch (ch) {
            case '+':
                sb.append(' ');
                break;
            case '#':
                sb.append(ch);
                fragment = true;
                break;
            case '%':
                if (!fragment) {
                    // fast hex decode
                    sb.append((char) ((Character.digit(s.charAt(++i), 16) << 4)
                            | Character.digit(s.charAt(++i), 16)));
                } else {
                    sb.append(ch);
                }
                break;
            default:
                sb.append(ch);
                break;
            }
        }
        return new String(sb.toString().getBytes(LATIN1), encoding);
    }
}

Related

  1. decode(final String str, final Charset charset)
  2. decode(String url, Charset charset)
  3. decode(String value, Charset charset)
  4. decode(String value, Charset charset)
  5. decodeCharset(String value, String charset)