PercentCodec { static void encode(final StringBuilder buf, final CharSequence content, final Charset charset, final BitSet safechars, final boolean blankAsPlus) { if (content == null) { return; } final CharBuffer cb = CharBuffer.wrap(content); final ByteBuffer bb = (charset != null ? charset : StandardCharsets.UTF_8).encode(cb); 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); } } }  static void encode(final StringBuilder buf, final CharSequence content, final Charset charset); static String encode(final CharSequence content, final Charset charset); static String decode(final CharSequence content, final Charset charset);  }
@Test public void testCoding() { final StringBuilder buf = new StringBuilder(); PercentCodec.encode(buf, "blah!", StandardCharsets.UTF_8); PercentCodec.encode(buf, " ~ ", StandardCharsets.UTF_8); PercentCodec.encode(buf, "huh?", StandardCharsets.UTF_8); MatcherAssert.assertThat(buf.toString(), CoreMatchers.equalTo("blah%21%20~%20huh%3F")); }