This is working code for a URI template (RFC 6570) implementation; when the character to render is not within a specific character set, it is needed to grab the UTF-8 representation of that character and encode each byte as a percent-encoded sequence.
The question is whether something more efficient than this exists?
private static String encodeChar(final char c)
{
final String tmp = new String(new char[] { c });
final byte[] bytes = tmp.getBytes(Charset.forName("UTF-8"));
final StringBuilder sb = new StringBuilder();
for (final byte b: bytes)
sb.append('%').append(UnsignedBytes.toString(b, 16));
return sb.toString();
}
Note: UnsignedBytes.toString()
is from Guava.
CharMatcher
to determine whether the current character in a string should be percent encoded or not. \$\endgroup\$