Java String Encode by Charset encoding(final String content, final Charset charset, final boolean blankAsPlus)

Here you can find the source of encoding(final String content, final Charset charset, final boolean blankAsPlus)

Description

encoding

License

Apache License

Declaration

public static String encoding(final String content, final Charset charset, final boolean blankAsPlus) 

Method Source Code


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

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.BitSet;

public class Main {
    /**/*  w  w w .ja  v  a  2  s .  co  m*/
     * Safe characters for x-www-form-urlencoded data, as per
     * java.net.URLEncoder and browser behaviour, i.e. alphanumeric plus
     * {@code "-", "_", ".", "*"}
     */
    private static final BitSet URLENCODER = new BitSet(256);
    private static final int RADIX = 16;

    public static String encoding(final String content, final Charset charset, final boolean blankAsPlus) {
        if (content == null) {
            return null;
        }
        StringBuilder buf = new StringBuilder();
        ByteBuffer bb = charset.encode(content);
        while (bb.hasRemaining()) {
            int b = bb.get() & 0xff;
            if (URLENCODER.get(b)) {
                buf.append((char) b);
            } else if (blankAsPlus && b == ' ') {
                buf.append('+');
            } else {
                buf.append("%");
                char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, RADIX));
                char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, RADIX));
                buf.append(hex1);
                buf.append(hex2);
            }
        }
        return buf.toString();
    }
}

Related

  1. encode(String value, Charset charset)
  2. encodeBase64(String s, Charset cs)
  3. encodeCHARSET(String string, Charset charset)
  4. encodeFormFields(final String content, final Charset charset)
  5. encodeOneChar(CharsetEncoder encoder, int uchar)
  6. ensureEncodingSet(List options, Charset defaultEncoding)
  7. getEncoder(Charset charset)
  8. getEncoder(Charset charset)
  9. getEncoder(String charset)