Java String Encode by Charset encodeFormFields(final String content, final Charset charset)

Here you can find the source of encodeFormFields(final String content, final Charset charset)

Description

encode Form Fields

License

Open Source License

Declaration

private static String encodeFormFields(final String content, final Charset charset) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.nio.ByteBuffer;

import java.nio.charset.Charset;

import java.util.BitSet;

public class Main {
    /**/*ww  w.  j  a  v a 2  s .c o  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;

    private static String encodeFormFields(final String content, final Charset charset) {
        if (content == null) {
            return null;
        }
        return urlEncode(content, charset != null ? charset : Charset.forName("UTF-8"), URLENCODER, true);
    }

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

Related

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