Skip to content

Instantly share code, notes, and snippets.

@davidjgraph
Last active November 10, 2016 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidjgraph/59275dbd898bd1bb4aeb7f3ec1521676 to your computer and use it in GitHub Desktop.
Save davidjgraph/59275dbd898bd1bb4aeb7f3ec1521676 to your computer and use it in GitHub Desktop.
encodeURIComponent in Java
// Starting from https://sangupta.com/tech/encodeuricomponent-and.html
public static final String ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()";
public static String encodeURIComponent2(String input, String charset)
{
if (input.isEmpty())
{
return input;
}
int l = input.length();
StringBuilder o = new StringBuilder(l * 3);
try
{
String e = "";
for (int i = 0; i < l; i++)
{
e = input.substring(i, i + 1);
if (ALLOWED_CHARS.indexOf(e) == -1)
{
byte[] b = e.getBytes(charset);
o.append(getHex(b));
continue;
}
o.append(e);
}
return o.toString();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return input;
}
private static String getHex(byte buf[])
{
StringBuilder o = new StringBuilder(buf.length * 3);
int n = 0;
for (int i = 0; i < buf.length; i++)
{
n = (int) buf[i] & 0xff;
o.append("%");
if (n < 0x10)
{
o.append("0");
}
o.append(Long.toString(n, 16).toUpperCase());
}
return o.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment