Last active
November 10, 2016 21:30
-
-
Save davidjgraph/59275dbd898bd1bb4aeb7f3ec1521676 to your computer and use it in GitHub Desktop.
encodeURIComponent in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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